-
Notifications
You must be signed in to change notification settings - Fork 0
/
Linked-List-Cycle.cpp
97 lines (76 loc) · 1.55 KB
/
Linked-List-Cycle.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
/*
* Song Qiang <keeyang@ustc.edu>
*/
/*
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
*/
#include <cmath>
#include <cassert>
#include <vector>
#include <numeric>
#include <iostream>
#include <algorithm>
#include <sstream>
#include <limits>
#include <utility>
#include <set>
#include <queue>
#include <stack>
#include <functional>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
void
printList(ListNode* h)
{
ListNode* t = h;
while (t != NULL)
{
cout << t->val << "\t";
t = t->next;
}
cout << endl;
}
void
clearList(ListNode* h)
{
while (h != NULL)
{
ListNode* t = h->next;
delete h;
h = t;
}
}
bool hasCycle(ListNode *head) {
if (head == NULL) return false;
ListNode* p1 = head;
ListNode* p2 = head->next;
while (p2 != NULL && p1 != p2)
{
p1 = p1->next;
p2 = p2->next;
if (p2 != NULL) p2 = p2->next;
}
return p2 != NULL;
}
};
int
main(int argn, char** argv)
{
ListNode* h = new ListNode(1);
h->next = new ListNode(2);
h->next->next = new ListNode(3);
h->next->next->next = new ListNode(4);
h->next->next->next->next = new ListNode(5);
Solution s;
s.printList(h);
s.printList(h);
s.clearList(h);
}