-
Notifications
You must be signed in to change notification settings - Fork 0
/
142_Linked List Cycle II.cpp
59 lines (55 loc) · 1.25 KB
/
142_Linked List Cycle II.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
#include <bits/stdc++.h>
using namespace std;
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *detectCycle(ListNode *head) {
ListNode *pslow = head, *pfast = head;
while (pslow!=NULL && pfast!=NULL && pfast->next!=NULL) {
pslow = pslow->next;
pfast = pfast->next->next;
if (pslow == pfast) {
pslow = head;
while (pslow != pfast) {
pslow = pslow->next;
pfast = pfast->next;
}
return pslow;
}
}
return NULL;
}
};
int main() {
Solution s;
ListNode *head = NULL;
int n, x;
cin >> n;
for (int i = 0; i < n; ++i) {
cin >> x;
ListNode node(x);
ListNode *p;
if (i == 0) {
head = &node;
p = head;
} else {
p->next = &node;
p = p->next;
}
}
ListNode *ans = s.detectCycle(head);
cout << ans->val << endl;
return 0;
}