双向链表

上一篇 / 下一篇  2012-06-10 21:58:19 / 个人分类:java


public class test1 {
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  TwoLinkList  test =new TwoLinkList();
  Link a1= new Link ("a1",1);
  test.inserthead(a1);
  test.deleteHead();
  
  Link a2= new Link ("a2", 14);
  test.inserthead(a2);
  Link a3= new Link ("a3", 12);
  test.inserthead(a3);
  Link a4= new Link ("a4", 3);
  test.inserthead(a4);
  Link a5= new Link ("a5", 23);
  test.inserthead(a5);
  
  Link a6= new Link ("a56", 213);
  test.inserthead(a6);
  test.deleteHead();
  test.displayNext();
  test.displayback();
 }
}
class Link{
 String name;
 int age;
 Link next;
 Link back;
 Link(String name, int age)
 {
  this.name=name;
  this.age=age;
  
 }
 
 void displayLink(){
  System.out.println("my name is "+name+",my age is "+age);
 }
}
class TwoLinkList{
 Link first;
 Link last;
 
 void inserthead(Link node){
  if(first==null){
   first=node;   
   last=first;
   last.next=first;
   //first.back=last;
  }
  else{
   first.next=node;
   node.back=first;
   first=first.next;
   }
     }
 
 void displayNext()
 {
  Link temp=last;
  while(temp!=null)
  {
   temp.displayLink();
   temp=temp.next;
  
  }
 }
 
 void displayback()
 {
  Link temp=first;
  while(temp!=null)
  {
   temp.displayLink();
   temp=temp.back;
  
  }
 }
 
 Link deleteHead()
 {
  Link temp;
  temp=first;
  if(first==null)
  {System.out.println("the list is null");}
  else if(first.back==null)
  {temp=first; first=null;}
  else if(first.back==null){
   first=null;
   last=null;
   
  }
  else{
   first.back.next=null;
   first=first.back;
   first.next=null;
  }
  return temp;
  
 
 }
}

TAG:

 

评分:0

我来说两句

Open Toolbar