1.双向链表的结构
单链表的优点是结构简单,缺点是不能直接访问其前驱结点。在单链表中要查找一个结点的前驱结点,时间复杂度为O(n)。为此,扩充单链表的结点结构,引入双向链表。使每个结点类都有一个属性,引用其前驱结点。
双链表的缺点是:对链表进行插入和删除元素时,每次要修改两次。优点是进行尾插和尾删操作时,时间复杂度为O(1),较单链表方便。
2.双向链表a的结点类
class Node{
int value;
Node next;
Node prev;
}
3.双向链表的操作
package com.xunpu.datastruct.list.linkedlist;
public class DoubleLinkedList {
class DNode{
int value;//值
DNode prev;//前驱
DNode next;//后继
DNode(int value){
this.value=value;
}
}
private DNode head;//头结点
private DNode last;//尾结点
/**
* 头插
* @param v
*/
public void addFront(int v){
DNode node=new DNode(v);
node.next=this.head;
this.head=node;
if(this.last==null){//如果没有最后一个结点,设置最后一个结点为node.
this.last=node;
}
}
/**
* 尾插
* @param v
*/
public void addBack(int v) {
DNode node = new DNode(v);
node.next = null;
if (this.head == null) {//如果当前链表没有一个结点,设置链表的头结点和尾结点是node。
this.last = this.head = node;
} else {
node.prev = this.last;
this.last.next=node;
this.last = node;
}
}
/**
* 头删
*/
public void popFront(){
this.head=this.head.next;
if(this.head==null){//如果尾删后没有一个结点,那么设置尾结点为null.
this.last=null;
}
}
/**
* 删除尾结点
*/
public void popBack() {
if (this.head.next == null) {//如果链表中只有一个结点,删除后链表为空,因此设置它们为null。
this.head = this.last = null;
} else {
this.last.prev.next = null;
}
}
}