您的位置:首页 > 其它

Leetcode 链表 Linked List Cycle II

2014-08-30 23:04 369 查看
本文为senlie原创,转载请保留此地址:http://blog.csdn.net/zhengsenlie


Linked List Cycle II

 Total Accepted: 20444 Total
Submissions: 66195My Submissions

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?

题意:给定一个单链表,判断该链表中是否存在环,如果存在,返回环开始的节点

思路:

1.定义两个指针,快指针fast每次走两步,慢指针s每次走一次,如果它们在非尾结点处相遇,则说明存在环

2.若存在环,设环的周长为r,相遇时,慢指针走了 slow步,快指针走了 2s步,快指针在环内已经走了 n环,

则有等式 2s = s + nr 既而有 s = nr

3.在相遇的时候,另设一个每次走一步的慢指针slow2从链表开头往前走。因为 s = nr,所以两个慢指针会在环的开始点相遇

复杂度:时间O(n)

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};

ListNode *detectCycle(ListNode *head) {
if(!head || !head->next) return NULL;
ListNode *fast, *slow, *slow2;
fast = slow = slow2 = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow && fast != NULL){
while(slow->next){
if(slow == slow2){
return slow;
}
slow = slow->next;
slow2 = slow2->next;
}
}
}
return NULL;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: