public class LinkedList01 {
public static void main(String[] args) {
//模拟一个简单的双向链表
Node jack = new Node("jack");
Node tom = new Node("tom");
Node wyt = new Node("WYT");
//连接三个节点形成双向链表
jack.next=tom;
tom.next=wyt;
wyt.pre=tom;
tom.pre=jack;
Node first=jack;//让first引用指向jack,就是双向链表的头节点
Node last=wyt;//让last引用指向wyt,就是双向链表的尾节点
System.out.println("======演示从头到尾进行遍历========");
/* //演示从头到尾进行遍历
while (true){
if (first==null){
break;
}
System.out.println(first);
first=first.next;
}*/
System.out.println("======演示从尾到头进行遍历========");
//演示从尾到头进行遍历
while (true){
if (last==null){
break;
}
System.out.println(last);
last=last.pre;
}
//演示链表的添加对象/数据的方便
//要求,是在tom----wyt插入对象smith
//1.先创建一个Node节点 name是smith
Node smith = new Node("smith");
tom.next=smith;
smith.next=wyt;
wyt.pre=smith;
smith.pre=tom;
System.out.println("======演示从头到尾进行遍历========");
//演示从头到尾进行遍历
while (true){
if (first==null){
break;
}
System.out.println(first);
first=first.next;
}
}
}
//定义一个Node类,Node对象表示双向链表的一个节点
class Node{
public Object item;//真正存放数据
public Node next;//指向后一个节点
public Node pre;//指向前一个节点
public Node(Object item) {
this.item = item;
}
@Override
public String toString() {
return "Node name="+item
;
}
简单模拟一个双向链表
最新推荐文章于 2024-07-06 14:54:18 发布