Skip to content

Instantly share code, notes, and snippets.

@michealbenedict
Created September 10, 2012 20:55
Show Gist options
  • Save michealbenedict/3693787 to your computer and use it in GitHub Desktop.
Save michealbenedict/3693787 to your computer and use it in GitHub Desktop.
package all;
public class FDList<T> {
public class Element{
T val1;
Element next;
Element prev;
public Element(T a, Element b, Element c){
val1=a;
next=b;
prev=c;
}
public T value(){
return this.val1;
}
}
public class Cursor{
private Element curr;
private Writer writer(){
Writer a =new Writer();
return a;
}
public Cursor( Element x ) { curr = x; }
public Element curr() { return this.curr ;}
public void prev() {curr= this.curr.prev; }
public void next() { curr=this.curr.next; }
}
public class Writer{//where is the cursor
public boolean insertBefore(T val) {
Element a=new Element(val, cu.curr,cu.curr.prev);
cu.curr.prev=a;
if(cu.curr.next==cu.curr)
cu.curr.next=a;
if(cu.curr.next.next==cu.curr)
cu.curr.next.next=a;
return true;
}
public boolean insertAfter(T val) {
Element a=new Element(val,cu.curr.next,cu.curr);
cu.curr.next=a;
if(cu.curr.prev.prev==cu.curr)
cu.curr.prev.prev=a;
if(cu.curr.prev==cu.curr){
cu.curr.prev=a;
}
return true;
}
public boolean delete() { //when the list is null, throw an error;when delete an element, the pointer will point to its previous element
if(cu.curr.next==cu.curr.prev && cu.curr.next==cu.curr){//only one element in the list
System.out.println("delete "+cu.curr.val1);
System.out.println();
throw new Error("the list is empty");
}
if(cu.curr.prev==cu.curr.next.next){//three elements in the list
cu.curr.next.prev=cu.curr.prev;
cu.curr.prev.next=cu.curr.next;
}
if(cu.curr.next==cu.curr.prev && cu.curr.next!=cu.curr){//two elements in the list
cu.curr.next.next=cu.curr.prev;
cu.curr.next.prev=cu.curr.prev;
}
System.out.println("delete "+ cu.curr.val1);
cu.curr.next.prev=cu.curr.prev;
cu.curr.prev.next=cu.curr.next;
Element a=cu.curr.prev;
cu.curr=a;
return true;
}
}
private Cursor cu ;
private Element head;
public Element head() { return this.head; }
public Cursor reader(T a) {
Element temp=cu.curr;
if(cu.curr==null)
throw new Error("no such element existing");
else{
do{
System.out.println(temp.val1);
if(temp.val1.equals(a)){
Cursor v=new Cursor(temp);
return v;
}
temp=temp.next;
}while(temp!=cu.curr);
throw new Error("no such element exiting");
}
}
public FDList (T val1){
Element a1=new Element(val1,null,null);
a1.next=a1;
a1.prev=a1;
cu=new Cursor(a1);
head=a1;
}
public static void main(String[] args){
FDList<String> f=new FDList<String> ("int");
f.cu.writer().insertAfter("bye");
f.cu.writer().insertBefore("hi");
f.cu.writer().insertAfter("good");
f.cu.writer().delete();
f.cu.writer().delete();
f.cu.writer().delete();
f.cu.writer().delete();
f.cu.writer().delete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment