Skip to content

Commit dce748f

Browse files
linked list cycle
1 parent e20198d commit dce748f

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

Java/linked-list.java

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* class ListNode {
4+
* int val;
5+
* ListNode next;
6+
* ListNode(int x) {
7+
* val = x;
8+
* next = null;
9+
* }
10+
* }
11+
*/
12+
public class Solution {
13+
public boolean hasCycle(ListNode head) {
14+
15+
if (head == null){
16+
return false;
17+
}
18+
19+
ListNode slowPtr = head;
20+
ListNode fastPtr = head;
21+
22+
/** Approach
23+
24+
// 1. if no cycle exists AND
25+
// a. if there are even number of nodes then fast pointer will be pointing to null.
26+
// b. else there are odd number of nodes then fast pointer will be pointing to last node.
27+
28+
// 2. if slow pointer meet fast pointer that interprets there exists a loop
29+
*/
30+
31+
while (fastPtr != null && fastPtr.next != null) {
32+
33+
// move slow pointer one node at a time
34+
slowPtr = slowPtr.next;
35+
36+
// move fast pointer two nodes at a time
37+
fastPtr = fastPtr.next.next;
38+
39+
if (slowPtr == fastPtr)
40+
return true;
41+
}
42+
43+
return false;
44+
}
45+
}

0 commit comments

Comments
 (0)