看书再多不如亲自动手,下面就是我自己实现的一个双向链表
public class MyLinked {
private Node head;
private Node tail;
public int len;
private static class Node{
private Node prev;
private Object data;
private Node next;
public Node(Object data){
this.data=data;
}
public Node(Object data,Node next,Node prev){
this.data=data;
this.next=next;
this.prev=prev;
}
}
/**
* 链表中添加元素
* @param data
*/
public void addData(Object data){
if (head==null){
head=new Node(data,null,null);
tail=head;
len=len+1;
}else{
Node newNode=new Node(data,null,tail);
tail.next=newNode;
tail=newNode;
len=len+1;
}
}
/**
* 在指定位置的后面插入元素,如果指定位置大于当前链表长度,则将元素添加到链表结尾。
* 如果当前链表为空,则将元素设置为链表的头结点
* @param data
* @param index
*/
public void addData(Object data,int index){
if (len==0){
head=new Node(data,null,null);
tail=head;
len=len+1;
}
if (index>len){
Node newNode=new Node(data,null,tail);
tail.next=newNode;
tail=newNode;
len=len+1;
}
else {
int i=0;
Node temp=head;
while (temp!=null){
while (++i==index){
Node newNode=new Node(data,temp.next,temp);
temp.next=newNode;
len=len+1;
break;
}
temp=temp.next;
}
}
}
/**
* 从前遍历打印链表元素
*/
public void traversingDataFromIndex(){
Node temp=head;
if (temp==null){
System.out.println("当前链表为空");
}else{
while (temp!=null){
System.out.println(temp.data);
temp=temp.next;
}
}
}
/**
* 后序遍历打印
*/
public void traversingDataFromLast(){
Node temp=tail;
if (temp==null){
System.out.println("当前链表为空");
}else{
while (temp!=null){
System.out.println(temp.data);
temp=temp.prev;
}
}
}
public static void main(String[] args) {
MyLinked myLinked=new MyLinked();
for (int i=0;i<10;i++){
myLinked.addData(i);
}
myLinked.traversingDataFromIndex();
myLinked.traversingDataFromLast();
}
}