http://oj.leetcode.com/problems/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?
思路:
如果前面Linked List Cycle的问题已经解决,再扩展一下就可以了。如果一步走两步走的方法在某个点交汇了,那么这个点肯定在环内。那么算出环的长度n,令某个节点从head出发先走n步,然后与head节点一起前进,那么交汇点就是环的起点。
1 class Solution { 2 public: 3 ListNode *detectCycle(ListNode *head) { 4 if (NULL == head) { 5 return NULL; 6 } 7 8 ListNode *curr = head, *next = head->next; 9 10 while (true) { 11 curr = curr->next; 12 13 int steps = 0; 14 15 while ((next != NULL) && (steps < 2)) { 16 next = next->next; 17 ++steps; 18 } 19 20 if (NULL == next) { 21 return NULL; 22 } 23 24 if (curr == next) { 25 break; 26 } 27 } 28 29 ListNode *next_head = head->next; 30 31 next = next->next; 32 33 while (curr != next) { 34 next = next->next; 35 next_head = next_head->next; 36 } 37 38 while (head != next_head) { 39 head = head->next; 40 next_head = next_head->next; 41 } 42 43 return head; 44 } 45 };