一、双向链表说明:
1. 以前所遇到的链表都只提供了从前向后遍历数组的功能,而双向链表提供了从最后向前遍历数组的功能。这是因为在双向链表中都有两个指向其他链表的引用。
2. 当然,双向链表也有它的缺点:每次插入和删除链结点的时候,都要处理四个引用;此外,双向链表的链结点比其他链表的链结点占用的空间要多。双向链表如下图所示:
二、Java语言描述双向链表:
package com.solid.link;
public class DoublyLinkedList {
//对第一个链结点的引用
private Link first;
//对最后一个链结点的引用
private Link last;
/**
* 构造方法
*/
public DoublyLinkedList() {
first = null;
last = null;
}
/**
* 判断是否为空
* @return
*/
public boolean isEmpty() {
return (first==null);
}
/**
* 插入到链表首部
* @param key
*/
public void insertFirst(int key) {
Link link = new Link(key);
if(isEmpty()) {
last = link;
} else {
first.previous = link;
}
link.next = first;
first = link;
}
/**
* 插入到链表最后
* @param key
*/
public void insertLast(int key) {
Link link = new Link(key);
if(isEmpty()) {
first = link;
} else {
last.next = link;
link.previous = last;
}
last = link;
}
/**
* 删除第一个链结点
*/
public void deleteFirst() {
if(first.next == null) {
last = null;
}
first.next.previous = null;
first = first.next;
}
/**
* 删除最后一个链结点
*/
public void deleteLast() {
if(first.next == null) {
first = null;
}
last.previous.next = null;
last = last.previous;
}
/**
* 删除任意一个链结点
* @param key
*/
public Link delete(int key) {
Link current = first;
while(current.iDate != key) {
current = current.next;
if(current == null) {
return null;
}
}
if(current == first)
first = current.next;
else
current.previous.next = current.next;
if(current == last)
last = current.previous;
else
current.next.previous = current.previous;
return current;
}
/**
* 从前向后遍历
*/
public void displayForward() {
Link current = first;
System.out.print("first-->last: ");
while(current != null) {
current.display();
current = current.next;
}
System.out.println();
}
/**
* 从后向前遍历
*/
public void displayBackward() {
Link current = last;
System.out.print("last-->first: ");
while(current != null) {
current.display();
current = current.previous;
}
System.out.println();
}
}