LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II

鏈表相關題node

141. Linked List Cyclespa

Given a linked list, determine if it has a cycle in it.指針

Follow up:
Can you solve it without using extra space? (Easy)code

 

分析:blog

採用快慢指針,一個走兩步,一個走一步,快得能追上慢的說明有環,走到nullptr尚未相遇說明沒有環。it

代碼:io

 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     bool hasCycle(ListNode *head) {
12         if (head == NULL) {
13             return 0;
14         }
15         ListNode* slow = head;
16         ListNode* fast = head;
17         while (fast != nullptr && fast->next != nullptr) {
18             slow = slow->next;
19             fast = fast->next->next;
20             if (slow == fast) {
21                 return true;
22             }
23         }
24         return false;
25     }
26 };

 

142. Linked List Cycle IIast

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.class

Note: Do not modify the linked list.List

Follow up:
Can you solve it without using extra space?(Medium)

 

分析:

1)同linked-list-cycle-i一題,使用快慢指針方法,斷定是否存在環,並記錄兩指針相遇位置(Z);
2)將兩指針分別放在鏈表頭(X)和相遇位置(Z),並改成相同速度推動,則兩指針在環開始位置相遇(Y)。
 
證實以下:
以下圖所示,X,Y,Z分別爲鏈表起始位置,環開始位置和兩指針相遇位置,則根據快指針速度爲慢指針速度的兩倍,能夠得出:
2*(a + b) = a + b + n * (b + c);即
a=(n - 1) * b + n * c = (n - 1)(b + c) +c;
注意到b+c剛好爲環的長度,故能夠推出,如將此時兩指針分別放在起始位置和相遇位置,並以相同速度前進,當一個指針走完距離a時,另外一個指針剛好走出 繞環n-1圈加上c的距離。
故兩指針會在環開始位置相遇。
 
代碼:
 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 *detectCycle(ListNode *head) {
12         if(head == nullptr) {
13             return 0;
14         }
15         ListNode* slow = head;
16         ListNode* fast = head;
17         while (fast != nullptr && fast->next != nullptr) {
18             slow = slow -> next;
19             fast = fast -> next -> next;
20             if(slow == fast){
21                 break;
22             }
23         }
24         if (fast == nullptr || fast->next == nullptr) {
25             return nullptr;
26         }
27         slow = head;
28         while (slow != fast) {
29             slow = slow->next;
30             fast = fast->next;
31         }
32         return slow;
33     }
34 };
相關文章
相關標籤/搜索