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?
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode *detectCycle(ListNode *head) { 12 /* 13 结题报告 14 首先要判断是否有环,详见Linked List Cycle 15 16 假设当前慢指针已经走了s步,则快指针已经走了2s步,环的长度是r,链表长是L,从头指针到环处是a,从环到相遇处长度为x 17 则 2s = s + nr; 所以s= nr; 18 a + x = s; 所以 a+x = nr; 19 a+x = (n-1)r + r; 20 a+x = (n-1)r + L-a; 21 因此a = (n-1)r + L-a-x; 22 所以下一次头指针和slow指针必然会相遇,而且相遇处为环开始的节点 23 24 */ 25 26 ListNode* fast = head; 27 ListNode* slow = head; 28 while(fast && fast->next){ 29 fast = fast->next->next; 30 slow = slow->next; 31 if(fast == slow) 32 break; 33 } 34 35 if(fast== NULL || fast->next == NULL) 36 return NULL; 37 38 ListNode* ptr = head; 39 while(ptr != slow){ 40 ptr = ptr->next; 41 slow = slow->next; 42 } 43 return ptr; 44 } 45 };
posted on 2015-08-30 11:34 horizon.qiang 阅读(116) 评论(0) 编辑 收藏 举报