您的位置:首页 > 其它

[Leetcode]Linked List Cycle II

2015-10-08 15:00 417 查看
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?

/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/*algorithm : hash solution
time O(n) space O(n)
*/
ListNode *detectCycle(ListNode *head) {
unordered_set<ListNode*>table;
ListNode* p = head;
while(p){
if(table.count(p))return p;
table.insert(p);
p = p->next;
}
return NULL;
}
};
class Solution {
public:
/*algorithm : two pointer solution
faster slower runner
time O(n) space O(1)
*/
ListNode *detectCycle(ListNode *head) {
if(!head)return NULL;
ListNode* faster = head,*slower = head;
do{
slower = slower->next;
faster = faster->next;
if(faster)faster = faster->next;
}while(faster && faster != slower);
if(!faster)return NULL; //no cycle
//
slower = head;
while(slower != faster){
slower = slower->next;
faster = faster->next;
}
return slower;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: