Wednesday, 6 March 2013

CircularLinkList


class Node<T>{
T data;
Node<T> next;

Node(T d)
{
data=d;

}
}
public class CircularList<T> {
Node<T> Head;
Node<T> Tail;
int TotalNodes;
public void insert(T d){
Node<T> newNode=new Node<T>(d);
TotalNodes++;
Node<T> T=Head;
if(Head==null){
Head=newNode;
Tail=newNode;
}
else{
newNode.next=T;
Tail.next=newNode;
Head=newNode;
}


}
/*
public int JosephusSolution(){
Node Temp=Head;
Node Prev=null;

int counter;

for(int i=1; i<TotalNodes;i++){

counter=(int)(Math.random()*(10)+1); // random counter to avoid baisness

for(int j=1;j<counter;j++){
Prev=Temp;
Temp=Temp.next;
}

Prev.next=Temp.next; // update reference for deletion

if(Temp==Head){ // if the deleted node is Head node
Tail.next=Head.next;
Head=Head.next;
}
if(Temp==Tail){ // if the deleted node is Tail node
Tail=Prev;
}
//Continue for next deletion
Temp=Prev.next;
}// end of outer loop

return Head.data; // return the Winner

}
*/
public void display(){
Node<T> T=Head;
System.out.println(T.data);
T=T.next;
while(T!=Head)
{
System.out.println(T.data);
T=T.next;
}
}

}

No comments:

Post a Comment