Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 329d390

Browse files
author
Ram swaroop
committed
linkedlist: loop detect done
1 parent b7765ca commit 329d390

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package me.ramswaroop.linkedlists;
2+
3+
import me.ramswaroop.common.SingleLinkedList;
4+
import me.ramswaroop.common.SingleLinkedNode;
5+
6+
/**
7+
* Created by IntelliJ IDEA.
8+
*
9+
* @author: ramswaroop
10+
* @date: 6/19/15
11+
* @time: 9:24 AM
12+
*/
13+
public class DetectLoop<E> extends SingleLinkedList<E> {
14+
15+
/**
16+
* Uses Flyod's Cycle Finding algorithm.
17+
* <p/>
18+
* This is the fastest method. Traverse
19+
* linked list using two pointers. Move one
20+
* pointer by one and other pointer by two.
21+
* If these pointers meet at some node then
22+
* there is a loop. If pointers do not meet
23+
* then linked list does not have loop.
24+
*
25+
* @param node
26+
* @return
27+
*/
28+
public boolean isLoopPresent(SingleLinkedNode<E> node) {
29+
SingleLinkedNode<E> prev = node, curr = node;
30+
while (curr != null && curr.next != null) {
31+
prev = prev.next;
32+
curr = curr.next.next;
33+
if (prev == curr) {
34+
return true;
35+
}
36+
}
37+
return false;
38+
}
39+
40+
public static void main(String a[]) {
41+
DetectLoop<Integer> linkedList = new DetectLoop<>();
42+
linkedList.add(11);
43+
linkedList.add(22);
44+
linkedList.add(33);
45+
linkedList.add(44);
46+
linkedList.add(55);
47+
linkedList.getNode(4).next = linkedList.getNode(3);
48+
System.out.println(linkedList.isLoopPresent(linkedList.getNode(0)));
49+
}
50+
}

0 commit comments

Comments
 (0)