1. 双向链表简介
Doubly Linked List is a variation of Linked list in which navigation is possible in both ways, either forward and backward easily as compared to Single Linked List. Following are the important terms to understand the concept of doubly linked list.
Link − Each link of a linked list can store a data called an element.
Next − Each link of a linked list contains a link to the next link
called Next.Prev − Each link of a linked list contains a link to the previous link
called Prev.LinkedList − A Linked List contains the connection link to the first
link called First and to the last link called Last.
双向链表是一种单链表的变体,双向链表可以双向遍历一个链表,维护一个head和tail节点实现,其实现细节和单链表相似度较高。
2. 双向链表demo
//DoubleList.java
package com.fqyuan.doublelinklist;
public class DoubleList<T> {
private Node head;
private Node tail;
private int num;
public DoubleList() {
head = new Node();
tail = new Node();
head.next = tail;
tail.prev = head;
}
public boolean isEmpty() {
return num == 0;
}
public int getNum() {
return num;
}
// Insert before the head node.
public boolean insertAtStart(T item) {
if (isEmpty()) {
head.value = item;
head.prev = null;
head.next = tail;
num++;
return true;
} else {
Node newNode = new Node();
newNode.value = item;
newNode.prev = null;
newNode.next = head;
head.prev = newNode;
head = newNode;
num++;
return true;
}
}
// Insert after the end node.
public boolean insertAtEnd(T item) {
if (isEmpty()) {
tail.value = item;