Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit 0757ba3

Browse files
committed
141. Linked List Cycle
1 parent 4d9f6ad commit 0757ba3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

141. Linked List Cycle.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
# 141. Linked List Cycle
2+
3+
### 2017-03-23
4+
5+
Given a linked list, determine if it has a cycle in it.
6+
7+
Follow up:
8+
Can you solve it without using extra space?
9+
10+
11+
12+
# Solution
13+
14+
```c++
15+
/**
16+
* Definition for singly-linked list.
17+
* struct ListNode {
18+
* int val;
19+
* ListNode *next;
20+
* ListNode(int x) : val(x), next(NULL) {}
21+
* };
22+
*/
23+
class Solution {
24+
public:
25+
bool hasCycle(ListNode *head) {
26+
if(head == NULL) { return false; }
27+
ListNode *a = head;
28+
ListNode *b = head;
29+
while (b->next != NULL && b->next->next != NULL) {
30+
a = a->next;
31+
b = b->next->next;
32+
if (a == b) { return true;}
33+
}
34+
return false;
35+
}
36+
};
37+
```
38+

0 commit comments

Comments
 (0)