File size: 750 Bytes
c574d3a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
class Loop{
Node head;
static class Node{
int data;
Node next;
Node(int d){
this.data =d;
next = null;
}
}
void push(int x){
Node t = new Node(x);
t.next = head;
head = t;
}
void isLoop(Node f){
Node p = f;
Node q = f;
do{
p = p.next;
q = q.next;
if(q!=null){
q = q.next;
}
else{
q = null;
}
} while(p!=null && q!=null && p!=q);
if(p==q){
System.out.println("Loop detected");
}
else{
System.out.println("Not a loop");
}
}
public static void main(String[] args){
Loop l = new Loop();
l.push(4);
l.push(5);
l.push(6);
l.push(7);
l.head.next = l.head;
l.isLoop(l.head);
}
}
|