Linked List Cycle
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Can you solve it without using extra space?
----------------------------- thinking -------------------------------------------------
the v2's speed is 2 times of v1's speed, then v1 and v2 will meet each other eventually
v*t = d + n1 * L
2*v*t = d + n2 * L
t = (n2 - n1) * L / v;
------------------------------------- codes ---------------------------------------------------
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head == NULL || head->next == NULL || head->next->next == NULL) {
return false;
}
//bug here: the starting v1 and v2 should be 1 and 2 steps ahead, or it will return at if (v1 == v2)
//v1 = head;
//v2 = head;
ListNode *v1 = head->next;
ListNode *v2 = head->next->next;
while (v2) {
if (v1 == v2) {
return true;
}
v1 = v1->next;
v2 = v2->next;
v2 = v2 == NULL? NULL:v2->next;
}
return false;
}
};
No comments:
Post a Comment