Get Start Node Of Loop In LinkList i.e while linked list have loop.
package linkelist.example;
// get Start Node Of Loop In LinkList i.e. while loop in linked list
public class getStartNodeOfLoopInLinkList {
Node startNode;
public static void main(String[] args) {
getStartNodeOfLoopInLinkList g = new getStartNodeOfLoopInLinkList();
Node n1 = new Node(10);
Node n2 = new Node(20);
Node n3 = new Node(30);
Node n4 = new Node(40);
Node n5 = new Node(50);
Node n6 = new Node(60);
Node n7 = new Node(70);
Node n8 = new Node(80);
g.startNode = n1;
n1.setNext(n2);
n2.setNext(n3);
n3.setNext(n4);
n4.setNext(n5);
n5.setNext(n6);
n6.setNext(n7);
n7.setNext(n8);
n8.setNext(n6);
Node loopNode = g.getStartNodeOfLoopInLinklist(g.startNode);
if (loopNode == null) {
System.out.println("Loop not present");
} else {
System.out.println("Start node of Loop is :" + loopNode.getData());
}
}
private Node getStartNodeOfLoopInLinklist(Node startNode) {
Node slowPointer = startNode; // Initially slowPointer is at starting location.
Node fastPointer = startNode; // Initially fastPointer is at starting location.
// If fastPointer encounters NULL, it means there is no Loop in Linked list.
while (fastPointer != null && fastPointer.getNext() != null) {
slowPointer = slowPointer.getNext(); // slowPointer moving one node at at time
fastPointer = fastPointer.getNext().getNext(); // fastPointer moving two nodes at at time
// if slowPointer and fastPointer meets, it means linked list contains loop.
if (slowPointer == fastPointer) {
// After meet, moving slowPointer to start node of list.
slowPointer = startNode;
// Moving slowPointer and fastPointer one node at a time till the time they
// meet at common point.
while (slowPointer != fastPointer) {
slowPointer = slowPointer.getNext();
fastPointer = fastPointer.getNext();
}
// returning start node of loop.
return slowPointer;
}
}
// this condition will arise when there is no loop in list.
return null;
}
}
package linkelist.example;
public class Node {
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getNext() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
}
Output:
Start node of Loop is :60
No comments:
Post a Comment