带环链表 II

思路

参考lintcode-102-带环链表

首先,利用快慢指针判断有无环,若遇到slow == fast时,存在环,跳出循环;

然后,使fast=head,slow不变,slow与fast同步移动,直至再次相遇,即是链表中环的起始节点。

code

/**
* Definition of ListNode
* class ListNode {
* public:
* int val;
* ListNode *next;
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The node where the cycle begins.
* if there is no cycle, return null
*/
ListNode *detectCycle(ListNode *head) {
// write your code here
ListNode * fast = head, *slow = head, *result = NULL; while(fast != NULL && fast->next != NULL) {
slow = slow->next;
fast = fast->next->next; if(fast == slow) {
break;
}
} if(fast != NULL && fast->next != NULL) {
fast = head;
while(fast != slow) {
slow = slow->next;
fast = fast->next;
}
result = fast;
}
return result;
}
};
05-18 04:10