- Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode142-cycle-list-2_set_solution.cpp
53 lines (47 loc) · 1.04 KB
/
leetcode142-cycle-list-2_set_solution.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
#include<iostream>
#include<set>
#include<algorithm>
usingnamespacestd;
/**
* Definition for singly-linked list.
*/
structListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
classSolution {
public:
ListNode *detectCycle(ListNode *head) {
set<ListNode*> st;
ListNode* p = head;
ListNode* res = NULL;
while(p != NULL)
{
if(st.insert(p).second == false) /* 向set中插入node失败,说明是第2次出现了,第1个出现第2次的 */
{
res = p;
return res;
}
p = p -> next;
}
returnNULL;
}
};
// Test
intmain()
{
Solution sol;
ListNode *n1 = newListNode(3);
ListNode *n2 = newListNode(2);
ListNode *n3 = newListNode(0);
ListNode *n4 = newListNode(-4);
n1->next = n2;
n2->next = n1;
n2->next = n3;
n3->next = n4;
n4->next = n2;
ListNode* meet = sol.detectCycle(n1);
cout << meet->val << endl;
return0;
}