双向链表
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。
双向链表节点图示:
双向链表示意图:
要注意的是,在对双向链表进行操作时,如插入,删除,和单链表是有区别的,双向链表需要同时修改两个方向上的指针(prev和next)
插入时指针的变化:
参考代码:
class ListNode{
public int data; //数据域
public ListNode prev; //前驱
public ListNode next; //后继
public ListNode(int data){
this.data=data;
}
}//节点类
class DoubleList{
public ListNode head; //头指针
public ListNode last; //尾指针
//头插法创建
public void addFirst(int data){
ListNode node=new ListNode(data);
if(this.head==null){
this.head=node;
this.last=node;
}else{
node.next=this.head;
this.head.prev=node;
this.head=node;
}
}
//尾插法创建
public void addLast(int data){
ListNode node=new ListNode(data);
if(this.head==null){
this.head=node;
this.last=node;
}else{
this.last.next=node;
node.prev=this.last;
this.last=node;
}
}
//打印双向链表
public void display(){
if(this.head==null){
return;
}
ListNode cur=this.head;
while(cur!=null){
System.out.print(cur.data+" ");
cur=cur.next;
}
System.out.println();
}
//获取长度
public int getLength(){
ListNode cur=this.head;
int count=0;
while(cur!=null){
count++;
cur=cur.next;
}
return count;
}
//找到index下标
public ListNode searchIndex(int index){
if(index<0 || index>getLength()){
return null;
}
ListNode cur=this.head;
while(index>0){
cur=cur.next;
index--;
}
return cur;
}
//在任意位置插入,第一个数据节点为0号下标
public boolean addIndex(int index,int data){
if(index==0){
addFirst(data);
return true;
}
if(index==getLength()){
addLast(data);
return true;
}
ListNode cur=searchIndex(index);
if(cur==null){
return false;
}
ListNode node=new ListNode(data);
node.next=cur; //相当于上图①步骤
node.prev=cur.prev; //相当于上图②步骤
cur.prev.next=node; //相当于上图③步骤
cur.prev=node; //相当于上图④步骤
return true;
}
}
public class Test {
public static void main(String[] args) {
DoubleList doubleList = new DoubleList();
doubleList.addLast(1);
doubleList.addLast(2);
doubleList.addLast(3);
doubleList.addLast(4);
doubleList.addLast(5);
doubleList.addIndex(3,99);
doubleList.display();
doubleList.addFirst(9);
doubleList.addFirst(8);
doubleList.addFirst(7);
doubleList.display();
}
}
//打印结果
1 2 3 99 4 5
7 8 9 1 2 3 99 4 5