您的位置:首页 > 其它

lintcode-103-带环链表 II

2017-07-14 09:14 330 查看

带环链表 II


给定一个链表,如果链表中存在环,则返回到链表中环的起始节点的值,如果没有环,返回null。

样例

给出 -21->10->4->5, tail connects to node index 1,返回10

挑战

不使用额外的空间

标签

链表 两根指针


思路

参考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;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: