1. 程式人生 > >LeetCode 206. Reverse Linked List

LeetCode 206. Reverse Linked List

hints eve 復雜度 more 返回值 solution gpo 虛擬節點 sed

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?

翻轉鏈表,非常經典的一道題目,不難,但是細節問題需要註意,這裏用三種方法來做,前兩種是叠代,最後一種是遞歸,個人認為第一種方法最好。

方法一:利用pre指針,追個翻轉節點

該方法從頭到尾遍歷鏈表,逐個翻轉節點就行,易錯點在於返回值一定是pre,而且pre的初始化要是null,這裏就是反轉之後鏈表的末尾,第一次我就寫成了cur

代碼如下:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         if (!head || !head->next) 
13 return head; 14 ListNode *pre = nullptr, *cur = head; //初始化一樣很重要 15 while (cur) 16 { 17 ListNode *t = cur->next; 18 cur->next = pre; 19 pre = cur; 20 cur = t; 21 } 22 //return cur; 23 return
pre; 24 } 25 };

時間復雜度:O(n)

空間復雜度:O(1)

方法二:

設置虛擬頭結點,每次在虛擬節點之後插入cur節點,最後直接返回dummy->next

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         if (!head || !head->next) 
13             return head;
14         ListNode *dummy = new ListNode(-1);
15         ListNode *pre = dummy;
16         ListNode *cur = head;
17         dummy->next = head;
18         while (cur && cur->next)
19         {
20             ListNode *t = cur->next;
21             cur->next = t->next;
22             t->next = pre->next;  //這裏註意  一定不要寫成t->next = cur;這麽做只有第一次交換是對的之後都不對
23             pre->next = t;
24         }
25         return dummy->next;
26     }
27 };

時間復雜度:O(n)

空間復雜度:O(1)

方法三:遞歸的方法,每次翻轉當前節點之後的所有節點,註意遞歸之後的操作以及最後的終止條件的確定

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
 6  *     ListNode(int x) : val(x), next(NULL) {}
 7  * };
 8  */
 9 class Solution {
10 public:
11     ListNode* reverseList(ListNode* head) {
12         if (!head || !head->next)
13             return head;
14         ListNode *newHead = reverseList(head->next);
15         head->next->next = head;
16         head->next = nullptr;
17         return newHead;
18     }
19 };

時間復雜度:O(n)

空間復雜度:O(n)

參考連接:

https://leetcode.com/problems/reverse-linked-list/solution/

https://leetcode.com/problems/reverse-linked-list/discuss/58130

LeetCode 206. Reverse Linked List