206. Reverse Linked List

来源:互联网 发布:淘宝店名片设计 编辑:程序博客网 时间:2024/05/17 07:01

这里写图片描述
这里写图片描述
迭代的方法

    ListNode* reverseList(ListNode* head) {        if(!head) return head;        ListNode *dummy=new ListNode(-1);        dummy->next=head;        ListNode*cur=head;        while(cur->next){            ListNode*tmp=cur->next;            cur->next=tmp->next;            // dummy->next=tmp;            // tmp->next=cur;            tmp->next=dummy->next;            dummy->next=tmp;        }        return dummy->next;    }

递归的方法

    ListNode* reverseList(ListNode* head) {        if(!head||!head->next) return head;        ListNode*p=head;        head=reverseList(p->next);        p->next->next=p;        p->next=NULL;        return head;    }