Tuesday, December 15, 2009

A Simple Implementation of LinkedList in java

public class MyLinkedList {

Entry head;
Entry last;
void add(Object obj){
if(last !=null){
last.next = new Entry(obj, null, null);
last.next.pre = last;
last = last.next;
}else{
last = head= new Entry(obj, null, null);

}
}
Object get(int index){
int i =0 ;
Entry prev = head;
while(i++ prev = prev.next;
}
return prev.value;
}
class Entry {
Object value;
Entry next;
Entry pre;

Entry(Object value, Entry next, Entry pre){
this.value = value;
this.next = next;
this.pre = pre;
}

}

public static void main(String []args){
MyLinkedList myList = new MyLinkedList();
myList.add("shiv1");
myList.add("shiv2");
myList.add("shiv3");
myList.add("shiv3");
System.out.println("print second "+(String)myList.get(3));

}

}

No comments:

Post a Comment