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