/
29_判断单链表是否有环.cpp
105 lines (93 loc) · 2.6 KB
/
29_判断单链表是否有环.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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <iostream>
#include <algorithm>
#include <unordered_set>
using namespace std;
/*
判断单链表是否有环
*/
class Node {
public:
Node(int data) : value(data) { next = nullptr; }
int value;
Node *next;
};
Node* EntryNodeOfLoop_1(Node* pHead)
{
if ((pHead == nullptr) || (pHead->next == nullptr) || (pHead->next->next == nullptr))
return nullptr;
/* 这么初始化快慢指针下面的while循环为true */
//Node *ptrFast = pHead;
//Node *ptrSlow = pHead;
Node *ptrFast = pHead->next->next;
Node *ptrSlow = pHead->next;
while (ptrFast != ptrSlow) {
if ((ptrFast->next == nullptr) || (ptrFast->next->next == nullptr))
return nullptr;
ptrFast = ptrFast->next->next;
ptrSlow = ptrSlow->next;
}
ptrFast = pHead;
while (ptrSlow != ptrFast) {
ptrFast = ptrFast->next;
ptrSlow = ptrSlow->next;
}
return ptrFast;
}
Node* EntryNodeOfLoop_2(Node* pHead)
{
unordered_set<Node *> mySet;
while (pHead != nullptr) {
if (!mySet.count(pHead)) {
mySet.insert(pHead);
pHead = pHead->next;
}
else
return pHead;
}
return nullptr;
}
int main() {
// 1->2->3->4->5->6->7->null
Node *head1 = &Node(1);
Node *temp = nullptr;
head1->next = &Node(2);
head1->next->next = &Node(3);
head1->next->next->next = &Node(4);
head1->next->next->next->next = &Node(5);
head1->next->next->next->next->next = &Node(6);
head1->next->next->next->next->next->next = &Node(7);
temp = EntryNodeOfLoop_1(head1);
if (temp == nullptr)
cout << "无环" << endl;
else {
cout << "有环, 入口: " << endl;
}
temp = EntryNodeOfLoop_2(head1);
if (temp == nullptr)
cout << "无环" << endl;
else {
cout << "有环, 入口: " << endl;
}
cout << "====================================" << endl;
// 1->2->3->4->5->6
head1 = &Node(1);
head1->next = &Node(2);
head1->next->next = &Node(3);
head1->next->next->next = &Node(4);
head1->next->next->next->next = &Node(5);
head1->next->next->next->next->next = &Node(6);
head1->next->next->next->next->next->next = head1->next->next->next; // 6->4
temp = EntryNodeOfLoop_1(head1);
if (temp == nullptr)
cout << "无环" << endl;
else {
cout << "有环, 入口: " << temp->value << endl;
}
temp = EntryNodeOfLoop_2(head1);
if (temp == nullptr)
cout << "无环" << endl;
else {
cout << "有环, 入口: " << temp->value << endl;
}
return 0;
}