【LeetCode】206. Reverse Linked List (2 solutions)


Reverse Linked List

Reverse a singly linked list.

click to show more hints.

Hint:

A linked list can be reversed either iteratively or recursively. Could you implement both?

 

解法一:非遞歸

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        else if(head->next->next == NULL)
        {
            ListNode* newhead = head->next;
            newhead->next = head;
            head->next = NULL;
            return newhead;
        }
        else
        {
            ListNode* pre = head;
            ListNode* cur = pre->next;
            pre->next = NULL;
            ListNode* post = cur->next;
            
            while(post != NULL)
            {
                cur->next = pre;
                pre = cur;
                cur = post;
                post = post->next;
            }
            cur->next = pre;
            return cur;
        }
    }
};

 

解法二:遞歸

每個節點都調到尾部去

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        if(head == NULL || head->next == NULL)
            return head;
        ListNode* newhead = head;
        while(newhead->next != NULL)
            newhead = newhead->next;
        reverse(head);
        return newhead;
    }
    ListNode* reverse(ListNode* head)
    {
        if(head->next == NULL)
            return head;
        else
        {
            ListNode* tail = reverse(head->next);
            tail->next = head;
            tail = tail->next;
            tail->next = NULL;
            return tail;
        }
    }
};


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM