forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
linkedListCycle.cpp
91 lines (79 loc) · 2.48 KB
/
linkedListCycle.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
// Source : https://oj.leetcode.com/problems/linked-list-cycle/
// Author : Hao Chen
// Date : 2014-07-03
/**********************************************************************************
*
* Given a linked list, determine if it has a cycle in it.
*
* Follow up:
* Can you solve it without using extra space?
*
*
**********************************************************************************/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
return hasCycle04(head);
return hasCycle03(head);
return hasCycle02(head);
return hasCycle01(head);
}
// using a map to store the nodes we walked
bool hasCycle01(ListNode *head) {
unordered_map<ListNode*,bool > m;
ListNode* p = head;
m[(ListNode*)NULL] = true;
while( m.find(p) == m.end() ) {
m[p] = true;
p = p -> next;
}
return p != NULL;
}
// Change the node's of value, mark the footprint by a special value
bool hasCycle02(ListNode *head) {
ListNode* p = head;
// using INT_MAX as the mark could be a bug!
while( p && p->val != INT_MAX ) {
p->val = INT_MAX;
p = p -> next;
}
return p != NULL;
}
/*
* if there is a cycle in the list, then we can use two pointers travers the list.
* one pointer traverse one step each time, another one traverse two steps each time.
* so, those two pointers meet together, that means there must be a cycle inside the list.
*/
bool hasCycle03(ListNode *head) {
if (head==NULL || head->next==NULL) return false;
ListNode* fast=head;
ListNode* slow=head;
do{
slow = slow->next;
fast = fast->next->next;
}while(fast != NULL && fast->next != NULL && fast != slow);
return fast == slow? true : false;
}
// broken all of nodes
bool hasCycle04(ListNode *head) {
ListNode dummy (0);
ListNode* p = NULL;
while (head != NULL) {
p = head;
head = head->next;
// Meet the old Node that next pointed to dummy
//This is cycle of linked list
if (p->next == &dummy) return true;
p->next = &dummy; // next point to dummy
}
return false;
}
};