-
Notifications
You must be signed in to change notification settings - Fork 0
/
linked_list_cycle.cpp
54 lines (45 loc) · 986 Bytes
/
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
// https://oj.leetcode.com/problems/linked-list-cycle/
// Date: Nov 09, 2014
#include <iostream>
struct ListNode
{
int val;
ListNode* next;
ListNode(int x): val(x), next(NULL) {}
};
class Solution
{
public:
bool hasCycle(ListNode *head)
{
if (head == NULL)
{
return false;
}
ListNode* h1 = head; // single step
ListNode* h2 = head; // double step
bool flag_cycle_present = false;
while ((h2->next != NULL) && (h2->next->next != NULL))
{
h2 = h2->next;
if (h2 == h1)
{
flag_cycle_present = true;
break;
}
h2 = h2->next;
if (h2 == h1)
{
flag_cycle_present = true;
break;
}
h1 = h1->next;
}
return flag_cycle_present;
}
};
int main(int argc, char* argv[])
{
Solution sln;
return 0;
}