package LinkedList;
//import LinkedList.detectLoop.Node;
//import LinkedList.linkedList.Node;
//import LinkedList.pallindromeLinkedList.Node;
public class detectLoop {
private class Node{
private int data;
private Node next;
}
static Node head=null;
Node tail=null;
int size=0;
public void addFirst(int item) {
Node nn=new Node();
nn.data=item;
nn.next=null;
if(this.size>=1) {
this.head.next=nn;
}
if(this.size==0) {
this.head=nn;
this.tail=nn;
size++;
}
else {
this.head=nn;
this.size++;
}
}
public void addLast(int item) {
Node nn=new Node();
nn.data=item;
nn.next=null;
if(this.size>=1) {
this.tail.next=nn;
}
if(this.size==0) {
this.head=nn;
this.tail=nn;
size++;
}
else {
this.tail=nn;
this.size++;
}
}
public void display() {
Node temp=this.head;
while(temp!=null) {
System.out.println(temp.data);
temp=temp.next;
}
}
/*static void detectandremoveloop(Node head) {
Node slow=head;
Node fast=head;
//slow=slow.next;
//fast=fast.next.next;
while(slow!=null && fast!=null && fast.next!=null) {
if(slow==fast)
break;
slow=slow.next;
fast=fast.next.next;
}
if(slow==fast) {
slow=head;
while(slow.next!=fast.next) {
slow=slow.next;
fast=fast.next;
}
fast.next=null;
}
}*/
public static boolean check_loop(){
Node p=head;
Node q=head;
while(p!=null && q!=null && q.next!= null) {
p=p.next;
q=q.next.next;
}
if(p==q) {
Node start=head;
Node loop=p;
while(loop.next!=start.next) {
loop=loop.next;
start=start.next;
}
loop.next=null;
return true;
}
else {
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
detectLoop list=new detectLoop();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(4);
list.addLast(5);
list.addLast(2);
list.addLast(3);
list.addLast(-1);
check_loop();
//removeloop(p,head);
//detectandremoveloop(head);
//System.out.println(display(head));
list.display();
}
}
i have done the code in eclipse slightly changed the format of taking inputs as given in CB ques.
i want to know the error in my logic,why is the check loop function not working