-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0141 环形链表.cpp
More file actions
73 lines (66 loc) · 1.54 KB
/
0141 环形链表.cpp
File metadata and controls
73 lines (66 loc) · 1.54 KB
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <cstdio>
#include <iostream>
#include <vector>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode * constructLinkedList(const vector<int>&v, int pos = -1) {
// construct linked list
ListNode *dum = new ListNode(0);
ListNode *p = new ListNode(v[0]);
dum->next = p;
ListNode *tail;
for (int i=1; i<v.size(); ++i) {
p->next = new ListNode(v[i]);
p = p->next;
tail = p;
}
// tail node point to node
p = dum->next;
while (pos-->=0) {
tail->next = p;
p = p->next;
}
return dum;
}
class Solution {
public:
bool hasCycle(ListNode *head) {
if (head==NULL)
return NULL;
ListNode* slow = head;
ListNode* fast = head;
while (fast) {
if (fast->next==NULL)
return false;
slow = slow->next;
fast = fast->next->next;
if (slow == fast)
return true;
}
return false;
}
};
int main() {
vector<int> v = {3,2,0,-4};
int pos = 1;
ListNode *dum = constructLinkedList(v, pos);
// print linked list
int cnt = 0;
ListNode *p = dum->next;
while (cnt++<=v.size() && p) {
if (cnt==v.size()+1)
cout << "> ";
cout << p->val << " ";
p = p->next;
}
cout << endl;
// check has cycle
Solution sol;
cout << "hasCycle: " << (sol.hasCycle(dum->next) ? "True" : "False") << endl;
delete p;
return 0;
}