Skip to content

Commit 55adc34

Browse files
Create 141. Linked List Cycle.md
1 parent 6bc355c commit 55adc34

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed
Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
## Problem
2+
3+
https://leetcode.com/problems/linked-list-cycle/
4+
5+
## Problem Description
6+
7+
Given head, the head of a linked list, determine if the linked list has a cycle in it.
8+
9+
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote the index of the node that tail's next pointer is connected to. **Note that pos is not passed as a parameter.**
10+
11+
Return true <i>if there is a cycle in the linked list.</i> Otherwise, return false.
12+
13+
**Example 1:**
14+
15+
**Input:** head = [3,2,0,-4], pos = 1
16+
17+
**Output:** true
18+
19+
**Explanation:** There is a cycle in the linked list, where the tail connects to the 1st node (0-indexed).
20+
<br>
21+
<br>
22+
23+
**Example 2:**
24+
25+
**Input:** head = [1,2], pos = 0
26+
27+
**Output:** true
28+
29+
**Explanation:** There is a cycle in the linked list, where the tail connects to the 0th node.
30+
<br>
31+
<br>
32+
33+
**Example 3:**
34+
35+
**Input:** head = [1], pos = -1
36+
37+
**Output:** false
38+
39+
**Explanation:** There is no cycle in the linked list.
40+
<br>
41+
<br>
42+
43+
## Code
44+
45+
- C++ Code:(**"Two Pointers Approach"**)
46+
47+
```cpp
48+
class Solution {
49+
public:
50+
bool hasCycle(ListNode *head) {
51+
52+
if(head == NULL)
53+
{
54+
return false;
55+
}
56+
57+
ListNode *fast = head;
58+
ListNode *slow = head;
59+
60+
while(fast != NULL && fast->next != NULL)
61+
{
62+
slow = slow->next;
63+
64+
fast = fast->next->next;
65+
66+
if(fast == slow)
67+
{
68+
return true;
69+
}
70+
}
71+
return false;
72+
}
73+
};
74+
```

0 commit comments

Comments
 (0)