Skip to content

Commit f8c5f8b

Browse files
committed
add: LinkedListLoop and LinkedListLoopNaive
1 parent f831832 commit f8c5f8b

File tree

2 files changed

+62
-0
lines changed

2 files changed

+62
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import DS.ListNode;
2+
3+
/*
4+
// Definition of ListNode:
5+
class ListNode {
6+
public int val;
7+
public ListNode next;
8+
public ListNode(int val) { this.val = val; }
9+
public ListNode(int val, ListNode next) {
10+
this(val);
11+
this.next = next;
12+
}
13+
}
14+
*/
15+
16+
17+
public class LinkedListLoop {
18+
public boolean linkedListLoop(ListNode head) {
19+
ListNode slow, fast;
20+
slow = fast = head;
21+
// Check both 'fast' and 'fast.next' to avoid null pointer
22+
// exceptions when we perform 'fast.next' and 'fast.next.next'.
23+
while (fast != null && fast.next != null) {
24+
slow = slow.next;
25+
fast = fast.next.next;
26+
if (fast == slow) return true;
27+
}
28+
return false;
29+
}
30+
}
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
4+
import DS.ListNode;
5+
6+
/*
7+
// Definition of ListNode:
8+
class ListNode {
9+
public int val;
10+
public ListNode next;
11+
public ListNode(int val) { this.val = val; }
12+
public ListNode(int val, ListNode next) {
13+
this(val);
14+
this.next = next;
15+
}
16+
}
17+
*/
18+
19+
20+
public class LinkedListLoopNaive {
21+
public boolean linkedListLoopNaive(ListNode head) {
22+
Set<ListNode> visited = new HashSet<>();
23+
ListNode curr = head;
24+
while (curr != null) {
25+
// Cycle detected if the current node has already been visited.
26+
if (visited.contains(curr)) return true;
27+
visited.add(curr);
28+
curr = curr.next;
29+
}
30+
return false;
31+
}
32+
}

0 commit comments

Comments
 (0)