package dsAndAlg;
public class linkedListLoop {
Node head = null;
public boolean hasLoop() {
Node temp = head;
Node slow = temp;
Node fast = temp;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
System.out.println("Hasloop");
return true;
}
}
System.out.println("No loop");
return false;
}
public void printNodes() {
Node temp = head;
while (temp != null) {
System.out.println(temp.data);
temp = temp.next;
}
}
public void findStartNode() {
Node temp = head;
Node slow = temp;
Node fast = temp;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
slow = temp;
while(slow != fast) {
slow = slow.next;
fast = fast.next;
}
System.out.println(slow.data);
}
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
linkedListLoop l = new linkedListLoop();
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);
l.head = 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);
// l.printNodes();
l.hasLoop();
l.findStartNode();
l.printNodes();
}
}
Comments
Post a Comment