双向链表是一种数据结构,它与单向链表相似,但每个节点有指向前一个节点和后一个节点的指针,这使得链表可以在任意方向上遍历。双向链表使得插入和删除节点的操作变得更加方便,因为可以直接访问前一个节点。
在Java中,可以使用类来实现双向链表。该类需要维护一个头节点和一个尾节点指针,以及每个节点的前一个节点和后一个节点指针。以下是双向链表类的示例代码:
public class DoublyLinkedList {
private Node head;
private Node tail;
private class Node {
int data;
Node prev;
Node next;
Node(int data) {
this.data = data;
}
}
public void addFirst(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
public void addLast(int data) {
Node newNode = new Node(data);
if (tail == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
}
public void removeFirst() {
if (head == null) {
throw new NoSuchElementException();
}
if (head == tail) {
head = null;
tail = null;
} else {
head = head.next;
head.prev = null;
}
}
public void removeLast() {
if (tail == null) {
throw new NoSuchElementException();
}
if (head == tail) {
head = null;
tail = null;
} else {
tail = tail.prev;
tail.next = null;
}
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
上述代码中,DoublyLinkedList
类包含一个内部类Node
,用于表示链表中的节点。addFirst
和addLast
方法用于在链表的起始和末尾添加新节点。removeFirst
和removeLast
方法用于从链表的起始和末尾删除节点。printList
方法用于遍历链表并打印节点的数据。
使用示例:
DoublyLinkedList list = new DoublyLinkedList();
list.addFirst(3);
list.addLast(5);
list.addFirst(1);
list.printList(); // Output: 1 3 5
list.removeLast();
list.removeFirst();
list.printList(); // Output: 3
在上面的示例中,我们创建了一个双向链表,并使用addFirst
和addLast
方法添加了几个节点。然后,我们使用printList
方法遍历和打印了链表。接下来,我们使用removeLast
和removeFirst
方法从链表的末尾和起点删除节点,最后再次使用printList
方法打印链表,以验证我们的删除操作是否有效。