-
Notifications
You must be signed in to change notification settings - Fork 0
/
2_6.cpp
78 lines (68 loc) · 1.29 KB
/
2_6.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//
// 2_6.cpp
//
//
// Created by Pengyan Qin on 6/17/15.
//
//
#include <iostream>
#include <unordered_map>
using namespace std;
struct node{
int key;
node* next;
node(int x):key(x), next(nullptr){}
};
node* createCircular(){
node *head = new node(3);
node *a = new node(4);
head->next = a;
node *b = new node(5);
a->next = b;
node *c = new node(6);
b->next = c;
node *d = new node(7);
c->next = d;
d->next = b;
return head;
}
// hash table
void circular(node *head){
if(!head)
return;
unordered_map<node*, bool> map;
while(head->next){
if(map[head] == false){
map[head] = true;
head = head->next;
}
else{
cout << head->key << endl;
return;
}
}
}
// fast pointer and slow pointer
void circular1(node *head){
node *fast = head;
node *slow = head;
while(fast && fast->next){
fast = fast->next->next;
slow = slow->next;
if(fast == slow)
break;
}
fast = head;
while(fast != slow){
fast = fast->next;
slow = slow->next;
}
cout << fast->key << endl;
return;
}
int main(){
node *head = createCircular();
circular(head);
circular1(head);
return 0;
}