Leetcode Linked List Cycle II
Linked List Cycle IITotal Accepted: 20444 Total Submissions: 66195My Submissions
Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull.
Follow up:
Can you solve it without using extra space?
A single-chain table is given to determine whether a ring exists in the linked list. If so, the node starting with the ring is returned.
Ideas:
1. Define two pointers. The fast pointer fast takes two steps at a time. The slow pointer s takes one step at a time. If they meet at a non-tail node, the loop exists.
2. if a ring exists and the circumference of the ring is set to r, when the encounter occurs, the slow pointer takes the slow step, the fast pointer takes the 2 s step, and the fast pointer has gone through the n ring in the ring,
Then there is an equation 2 s = s + nr and s = nr
3. When encountering each other, set another slow pointer slow2 to go forward from the beginning of the linked list. Because s = nr, the two slow pointers will meet at the starting point of the ring.
Complexity: time O (n)
struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {}};ListNode *detectCycle(ListNode *head) {if(!head || !head->next) return NULL;ListNode *fast, *slow, *slow2;fast = slow = slow2 = head;while(fast && fast->next){fast = fast->next->next;slow = slow->next;if(fast == slow && fast != NULL){while(slow->next){if(slow == slow2){return slow;}slow = slow->next;slow2 = slow2->next;}}}return NULL;}