1. 程式人生 > >java的雙向連結串列簡單實現

java的雙向連結串列簡單實現



package com.test;


public class SecondTest {

 public static void main(String[] args) {
  DoubleList test=new DoubleList();
  test.InsertData("xize");
  test.InsertData("ze");
  test.InsertData("li");
  test.InsertData("han");
  test.display();
  System.out.println();
  test.LastDisplay();
  System.out.println("陣列資料的個數:  "+test.sum);
  test.InsertAfter("ze", "haorizi");
  test.display();
  //查詢存在的資料
  System.out.println(test.FindData("ze"));
  //查詢不存在的資料
  System.out.println(test.FindData("mei"));

 }

}
//建立節點類
class Node{
 Node next;//後節點
 Node pre;//前節點
 Object data;//資料域
 public Node() {
  
 }
 public Node(Object object,Node pre,Node next){
  this.data=object;
  this.pre=pre;
  this.next=next;
 }
}
//雙向連結串列類
class DoubleList{
 Node first;
 int sum;
 public DoubleList() {
  first=new Node(0, null, null);
  sum=0;
 }
 //獲取最後一個節點
 public Node GetLast(){
  Node node=first;
  while(node.next!=null){
   node=node.next;
  }
       return node;
 }
 //插入節點資料
 public void InsertData(Object object){
  Node node=GetLast();
  Node newnode=new Node(object, node,null);
  node.next=newnode;
  sum++;
 }
 //前序遍歷
 public void display(){
  System.out.println("前序遍歷");
  Node temp=first.next;
  while(temp!=null){
   System.out.print(temp.data+" ");
   temp=temp.next;
  }
  
 }
 //後序遍歷
 public void LastDisplay(){
  System.out.println("後序遍歷");
  Node temp=GetLast();
  while(temp.pre!=null){
   System.out.print(temp.data+" ");
   temp=temp.pre;
  }
 }
 //查詢某個資料
 public boolean FindData(Object object){
  Node temp=first.next;
  
  //
  while(!temp.data.equals(object)){
   temp=temp.next;
   if(temp.next==null){
    break;
   }
  }
  if(temp.next==null){
   return false;
  }else{
   return true;
  }
  
 }
 //插入在某一個數據後的資料
 public void InsertAfter(Object object,Object data){
  Node temp=first.next;
  while(!temp.data.equals(object)){
   temp=temp.next;
  }
  Node node =new Node(data, temp, temp.next);
  temp.next.pre=node;
  temp.next=node;
  
 }
 
}