Skip to content

Commit a8663b4

Browse files
committed
linked_list_cycle
1 parent 36a5a37 commit a8663b4

File tree

2 files changed

+22
-1
lines changed

2 files changed

+22
-1
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -123,7 +123,8 @@ Golang solution for leetcode. For each problem, there is a simple *_test.go to t
123123
#### [137. single number II](https://github.com/hitzzc/go-leetcode/tree/master/single_number_II)
124124
#### [138. copy_list_with_random_pointer](https://github.com/hitzzc/go-leetcode/tree/master/copy_list_with_random_pointer)
125125
#### [139. word break](https://github.com/hitzzc/go-leetcode/tree/master/word_break)
126-
#### [140. word break II](https://github.com/hitzzc/go-leetcode/tree/master/word_break II)
126+
#### [140. word break II](https://github.com/hitzzc/go-leetcode/tree/master/word_break_II)
127+
#### [141. Linked List Cycle](https://github.com/hitzzc/go-leetcode/tree/master/linked_list_cycle)
127128

128129

129130

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
struct ListNode {
2+
int val;
3+
ListNode *next;
4+
ListNode(int x) : val(x), next(NULL) {}
5+
};
6+
class Solution {
7+
public:
8+
bool hasCycle(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 false;
16+
slow = slow->next;
17+
}
18+
return true;
19+
}
20+
};

0 commit comments

Comments
 (0)