定义
双向链表也叫双链表,是链表的一种,它的每个数据结点中都有两个指针,分别指向直接后继和直接前驱。所以,从双向链表中的任意一个结点开始,都可以很方便地访问它的前驱结点和后继结点。一般我们都构造双向循环链表。
结构图:
实现代码
/**
* 定义一个节点类
*/
public class Link {
public int data; //数据
public Link next; //下一个节点
public Link previous;//上一个节点
public Link(int data){
super();
this.data = data;
}
public void print(){
System.out.println("[ " + data + " ]");
}
}
public class DoubleLinkList {
private Link first;
private Link last;
public DoubleLinkList(){
first = null;
last = first;
}
/**
* 头部插入
* @param data
*/
public void insertFirst(int data){
Link newNode = new Link(data);
if (first == null){
//链表为空,last指向新的节点
last = newNode;
}else {
//如果不是第一个节点
first.previous = newNode;
}
newNode.next = first; //将新节点的next指向first
first = newNode; // first 指向新节点
}
/**
* 尾部插入
*/
public void insertLast(int data){
Link newnode = new Link(data);
if(first == null){
first = newnode;
}else {
newnode.previous = last;
last.next = newnode;
}
last = newnode;
}
public void insertAfter(int key,int data){
Link newdata = new Link(data);
Link current = first;
//循环找出要插入key的节点
while ((current != null)&&(current.data != key)){
current = current.next;
}
//如果没有找到key值相等的节点
if (current == null){
if (first == null){
//链表为空
first = newdata;
last = newdata;
}else {
//在尾部插入节点
last.next = newdata;
newdata.previous = last;
last = newdata;
}
}else {
if (current == last){
newdata.next = null;
last = newdata;
}else {
newdata.next = current.next;
current.next.previous = newdata;
}
current.next = newdata;
newdata.previous = current;
}
}
}