forked from liuyubobobo/Play-Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain2.cpp
59 lines (47 loc) · 1.46 KB
/
main2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
/// Source : https://leetcode.com/problems/linked-list-cycle/description/
/// Author : liuyubobobo
/// Time : 2017-11-02
#include <iostream>
#include <unordered_set>
using namespace std;
/// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
/// Two Pointers - fast and slow
/// faster pointer moves two steps a time, and slow pointer moves one step a time.
///
/// faster pointer will meet slow pointer eventually.
/// Simple prove: suppose faster pointer is x steps behind slow pointer
/// if x == 1, then in the next time, fast pointer will meet slow pointer
/// if x > 1, then in the next tme, fast pointer will get one step closer to slow pointer
/// the process continues until faster pointer is just one step behind slow pointer
/// thenm in the next time, they meet together:)
///
/// Time Complexity: O(n)
/// Space Complexity: O(1)
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL)
return false;
if(head->next == NULL)
return false;
ListNode* slow = head;
ListNode* fast = head->next;
while(fast != slow){
if(fast->next == NULL)
return false;
if(fast->next->next == NULL)
return false;
fast = fast->next->next;
slow = slow->next;
}
return true;
}
};
int main() {
return 0;
}