Skip to content

Commit db5c848

Browse files
committed
linked_list_cycle_II
1 parent a8663b4 commit db5c848

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

Diff for: README.md

+1
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,7 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
125125
#### [139. word break](https://github.com/hitzzc/go-leetcode/tree/master/word_break)
126126
#### [140. word break II](https://github.com/hitzzc/go-leetcode/tree/master/word_break_II)
127127
#### [141. Linked List Cycle](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle)
128+
#### [142. Linked List Cycle II](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle_II)
128129

129130

130131

Diff for: linked_list_cycle_II/linked_list_cycle_II.cpp

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
struct ListNode {
2+
int val;
3+
ListNode *next;
4+
ListNode(int x) : val(x), next(NULL) {}
5+
};
6+
class Solution {
7+
public:
8+
ListNode* detectCycle(ListNode *head) {
9+
ListNode* fast = head;
10+
ListNode* slow = head;
11+
bool first_step = true;
12+
while (first_step || fast!=slow){
13+
first_step = false;
14+
for (int i = 0; i < 2 && fast!=NULL; ++i) fast = fast->next;
15+
if (fast==NULL) return NULL;
16+
slow = slow->next;
17+
}
18+
int steps = 1;
19+
while (fast->next != slow){
20+
fast = fast->next;
21+
++steps;
22+
}
23+
fast = slow = head;
24+
for (int i = 0; i < steps; ++i) fast = fast->next;
25+
while (fast!=slow){
26+
fast = fast->next;
27+
slow = slow->next;
28+
}
29+
return slow;
30+
}
31+
};

0 commit comments

Comments
 (0)