您的位置:首页 > 其它

LeetCode - Linked List Cycle II

2014-01-13 21:45 609 查看
Linked List Cycle II

2014.1.13 21:43

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?

Solution:

  This problem doesn't only ask you to check if there is a loop in the list, but also to find out where you enter the loop.

  It is a bit tricky to solve this problem, if you are too accustomed to that "chasing method" that we mentioned in Linked List Cycle.

  Since you only have a "next" pointer, what you can do is to check if $ptr or $ptr->next satisfy some specific property.

  See the following linked list:

  


  Node 2 is the entrance of the loop. Both node 1 and node 4 points to it. If you start traversing the list, you are sure to reach node 2 first and node 4 later. If there is a $ptr pointing to node 4, you reach $ptr->next before you reach $ptr,right? In a normal linked list, this will never happen. That's how we use abnormal condition to detect this abnormal node.

  This problem doesn't use a chasing strategy with two pointers. But it requires one-by-one probing for all nodes until the right one is found, with each probing having O(n) time complexity. Therefore, the overall time complexity is O(n^2), space complexity is O(1).

Accepted code:

// 1CE, 2TLE, 1AC, foolish mistake..
/**
* Definition for singly-linked list.
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == nullptr){
return nullptr;
}

ListNode *ptr, *res;

res = head;
while(res != nullptr){
ptr = head;
// Forgot to check nullptr, added by the way later.
while(ptr != res->next && ptr != nullptr){
if(ptr == res){
// ptr reaches res first, not what we expect
break;
}
// 1TLE here, forgot to move forward...
// 1CE here, ';' is missing!!!!
ptr = ptr->next;
}
if(ptr == res->next){
// $ptr reaches res->next first, that means $res->next is the start of the loop
// while $res is the end of the loop, thus $ptr = $res->next is the result we want
return ptr;
}else{
// 1TLE here, forgot to move forward..
res = res->next;
}
}

return nullptr;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: