反转链表

递归

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head==NULL||head->next==NULL)  return head;
        //先反转head后面的链表,最后将head接在新链表最后即可
        auto tail=reverseList(head->next);
        //将head从新链表尾部接上去
        head->next->next=head;
        head->next=NULL;
        return tail;//tail是反转后的链表的新头节点
    }
};

迭代

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(!head)  return NULL;
        auto a=head;auto b=head->next;
        a->next=NULL;
        while(a&&b)
        {
            auto c=b->next;
            b->next=a;
            a=b;
            b=c;
        }
        return a;
    }
};
posted @ 2023-03-25 15:30  穿过雾的阴霾  阅读(18)  评论(0)    收藏  举报