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 II 的基础上(http://blog.youkuaiyun.com/ayst123/article/details/38774927),把return true换成return findnode()即可
假设fast和slow相遇在环中A点,如果slow 走了n 步,则fast走了2n步。此时,如果fast不动,slow再走n步就会追上n步。再如果fast从head开始,则fast和slow还会在A点相遇。 很容易想到,他们之前肯定还会再遇到至少一次,这个点就是环入口。
C++
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* findnode(ListNode* head, ListNode* slow){
ListNode* fast = head;
while (fast!=slow){
fast = fast->next;
slow = slow->next;
}
return fast;
}
ListNode *detectCycle(ListNode *head) {
ListNode* fast = head;
ListNode* slow = head;
while (fast!=NULL and fast->next!=NULL){
fast = fast->next->next;
slow = slow->next;
if (fast==slow){
return findnode(head,slow);
}
}
return NULL;
}
};