Linked List related questions
141. Linked List Cycle
Given A linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space? (easy)
Analysis:
Adopt quick and slow hands, a walk two steps, a walk one step, fast can catch on the note has ring, go to nullptr haven't met explanation no ring.
Code:
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 classSolution {Ten Public: One BOOLHascycle (ListNode *head) { A if(Head = =NULL) { - return 0; - } thelistnode* slow =head; -listnode* fast =head; - while(Fast! = nullptr && Fast->next! =nullptr) { -slow = slow->Next; +Fast = Fast->next->Next; - if(Slow = =fast) { + return true; A } at } - return false; - } -};
142. Linked List Cycle II
Given a linked list, return the node where the cycle begins. If There is no cycle, return null
.
Note:do not modify the linked list.
Follow up:
Can you solve it without using extra space? (Medium)
Analysis:
1) with Linked-list-cycle-i, use the fast and slow pointer method, determine whether there is a ring, and record the two pointer meet position (z); 2) Place the two pointers in the chain header (X) and the meeting position (z), and change to the same speed, then the two pointers meet at the beginning of the ring (Y). The proof is as follows: as shown, x, Y, Z are the start position of the linked list, the ring start position and the two pointer meet position, according to the fast pointer speed is twice times the slow pointer speed, can be obtained: (A + b) = a + B + N * (b + c); i.e. a= (n-1) * b + N 1) (b + C) +c; Notice that the b+c happens to be the length of the ring, so it can be launched, such as the two hands at the beginning position and meet position, and at the same speed forward, when a pointer walk the distance A, the other pointer just out of the ring around the n-1 ring plus the distance of C. So the two pointers will meet at the beginning of the ring.
Code:
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 classSolution {Ten Public: OneListNode *detectcycle (ListNode *head) { A if(Head = =nullptr) { - return 0; - } thelistnode* slow =head; -listnode* fast =head; - while(Fast! = nullptr && Fast->next! =nullptr) { -slow = slowNext; +Fast = fast, NextNext; - if(Slow = =fast) { + Break; A } at } - if(Fast = = Nullptr | | fast->next = =nullptr) { - returnnullptr; - } -slow =head; - while(Slow! =fast) { inslow = slow->Next; -Fast = Fast->Next; to } + returnslow; - } the};
LeetCode141 Linked List Cycle. LeetCode142 Linked List Cycle II