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?
头结点到cycle begins的点 距离是A, cycle begins的点 到快慢结点相遇的 点的距离是B
A+B+N = 2*(A+B)
A+B = N
所以 快慢指针相遇后,从头结点开始再跑一个慢指针,直到2个慢的相遇,相遇的点就是cycle begin
class Solution { public: ListNode *detectCycle(ListNode *head) { ListNode* slow = head; ListNode* fast = head; while(slow != NULL && fast != NULL && fast->next != NULL) { slow = slow->next; fast = fast->next->next; if(slow == fast) break; } // fast 遇到空指针说明没有环 if(fast == NULL || fast->next == NULL) return NULL; // slow 从头跑一遍 slow = head; while(slow!=fast) { slow = slow->next; fast = fast->next; } return slow; } };