Linked List Cycle II
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?
思路:
在上一题的基础上,假设head到环入口的距离为a,相遇点到环入口的距离为b,换的周长为r,则第一次相遇时有
2*(a+b) = a + b + nr
a = nr - b
也就是说如果从相遇点和head处同时出发两个指针,步数一样,那么就会在环入口相遇,据此可以获得入口的指针
代码
ListNode *detectCycle(ListNode *head) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. if(head == NULL) return NULL; if(head->next == NULL) return NULL; ListNode *slow = head, *fast = head; while(true){ if(fast && fast->next){ fast = fast->next->next; } else{ return NULL; } slow = slow->next; if(fast == slow) break; } ListNode *p1 = head, *p2 = slow; while(true){ if(p1 == p2) return p1; p1 = p1->next; p2 = p2->next; } }