-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0142 环形链表 II.cpp
More file actions
79 lines (72 loc) · 1.72 KB
/
0142 环形链表 II.cpp
File metadata and controls
79 lines (72 loc) · 1.72 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
74
75
76
77
78
79
#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:
ListNode *detectCycle(ListNode *head) {
if (head==NULL)
return NULL;
ListNode* slow = head;
ListNode* fast = head;
while (fast!=NULL) {
if (fast->next==NULL)
return NULL;
slow = slow->next;
fast = fast->next->next;
if (fast==slow) {
fast = head;
while (fast != slow) {
slow = slow->next;
fast = fast->next;
}
return fast;
}
}
return NULL;
}
};
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;
// detectCycle
Solution sol;
cout << "detectCycle: " << sol.detectCycle(dum->next)->val << endl;
delete p;
return 0;
}