用java实现双向链表
双向链表的定义和初始化
定义
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继(next)和直接前驱(prev/prior)。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。如下图所示:
初始化
以java为例,对于双向链表的初始化,我们一般先定义出一个链表MyLinkedList(head,last),在定义节点node信息(next,prev,val)
public class MyLinkedList {
public Node head;
public Node last;
public MyLinkedList(){
head=last=null;
}
public class Node {
public Node prev;
public Node next;
public String val;
public Node(String val){
this.val=val;
}
}
双向链表的创建(尾插)
同单链表相比,双链表仅是各节点多了一个用于指向直接前驱的指针域。因此,我们可以在单链表的基础轻松实现对双链表的创建。
需要注意的是,与单链表不同,双链表创建过程中,每创建一个新节点,都要与其前驱节点建立两次联系,分别是:
将新节点的 prev 指针指向直接前驱节点;
将直接前驱节点的 next 指针指向新节点;
以尾插为例:
public boolean add(String e){
Node node=new Node(e);
if(head==null)
head = last = node;
else {
last.next=node;
node.prev=last;
last=last.next;
}
return true;
}
双向链表指定位置插入
对于这种问题,我们需要分情况考虑:
1.指定位置(index)是否合法,即index不能为负数也不能大于链表节点个数(size);
2.链表为空的情况(size0);
3.插入位置为链表头或者链表尾(index0,index==size);
4.其他任意位置插入。
具体分情况的代码示例如下:
public void add(int index,String e){
if(index>size()||index<0)
throw new ArithmeticException();
else if (size()==0){
Node node=new Node(e);
head=last=node;
}
else if (index==0){
Node node=new Node(e);
node.next=head;
head.prev=node;
head=node;
}
else if (index == size()) {
Node node=new Node(e);
last.next=node;
node.prev=last;
last=last.next;
}
else {
Node node=new Node(e);
Node cur=head;
for (int i=0;i<index-1;i++){
cur=cur.next;
}
cur.next.prev=node;
node.prev=cur;
node.next=cur.next;
cur.next=node;
}
}
运行结果如下:
在第2个位置插入一个Q,结果如下
总结
双向链表不难,主要在于明白链表这种存储方式的特点以及节点间或者各引用间的逻辑关系,要保持思路清楚,以后再分享更多有关双向链表的知识吧~