Leetcode Note: Linked List Cycle 2
I. Description
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up: Can you solve it without using extra space?
Ii. Question Analysis
In the Linked List Cycle question, two pointers fast and slow are used to check whether the Linked List has loops. Based on this question, the central portal location of the Linked List must be given, and the space complexity should also be paid attention. For ease of interpretation, the following is a chain table:
The distance between the head node and the entrance to the ring of the linked list isX, The Ring length isY, UsefastAndslowTwo pointers,fastThe pointer moves forward two steps at a time,slowPointers move one step forward, then they will eventuallyKEncounter at the node.fastThe pointer has passed through the ring.mCircle,slowPointer walking in the ringnCircle, there are:
fastDistance:2*t = X+m*Y+K <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Authorization + y/authorization + signature + PC9wPg0KPHA + signature/Signature + 0 + signature/g0/bKsaOsv8nKudPDtdrI/Signature + signature + cew19 + signature + 1signature v69kyvmzq + release + 0 + s8Y29kZT5jeWNsZVN0YXJ0PC9jb2RlPs/g0/ajrLjDzrvWw77NysfBtLHt1tC7t7XEyOu/2rSmoaM8L3A + release "brush: java; "> #include using namespace std;struct ListNode{ int value; ListNode* next; ListNode(int x) :value(x), next(NULL){}};class Solution{public: ListNode *detectCycle(ListNode *head) { if (head == NULL || head->next == NULL || head->next->next == NULL) return head; ListNode* fast = head; ListNode* slow = head; while (fast->next->next) { fast = fast->next->next; slow = slow->next; if (fast == slow) { ListNode* cycleStart = head; while (slow != cycleStart) { slow = slow->next; cycleStart = cycleStart->next; } return cycleStart; } } return NULL; }};
A chain table starts with the second node:
Iv. Summary
When answering questions related to the linked list, you need to draw more pictures and find patterns. Otherwise, you may encounter various boundary problems.