Java代码:
package com.linked;
class B{
public int data; //数据
public B before=null; //前驱
public B after=null; //后继
public B(){
}
public B(int data,B before,B after){
this.data=data;
this.before=before;
this.after=after;
}
}
public class Test2 {
public static void main(String[] args) {
B head=new B(0,null,null);
B p=head; //p 用于交换位置
for (int i=1;i<10;i++){
B e=new B(i,null,null);
p.after=e; //前一个指针after指向e
e.before=p; //e的指针before指向前一个
p=e; //交换位置
}
B out1,out2;
out1=head; //用于链表正向输出
out2=p; //用于链表逆向输出
while(out1.after!=null){
System.out.print(out1.data);
out1=out1.after;
}
System.out.print(out1.data+"\n"); //输出最后一个,因为它的指针(地址after)为空
while(out2.before!=null){
System.out.print(out2.data);
out2=out2.before;
}
System.out.println(out2.data);//输出最后一个,因为它的指针(地址before)为空
}
}
测试结果: