206. 反转链表

206. 反转链表

递归

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == nullptr || head->next == nullptr)
            return head;
        ListNode* next = head->next;
        ListNode* ret = reverseList(head->next);
        next->next = head;
        head->next = nullptr;
        return ret;
    }
};

迭代

class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == nullptr || head->next == nullptr)
            return head;
        ListNode *prev=nullptr,*curr=head,*next=nullptr;
        while(curr!=nullptr) {
            next = curr->next;
            curr->next = prev;
            prev = curr;
            curr = next;
        }
        return prev;
    }
};
posted @ 2020-09-09 11:02  pusidun  阅读(78)  评论(0编辑  收藏  举报