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;
  
 }
 
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值