在Java中,可以使用自定義的雙向鏈表類來實現雙向鏈表。以下是一個簡單的雙向鏈表的實現示例:
public class DoublyLinkedList<T> {
private Node<T> head; // 鏈表頭節點
private Node<T> tail; // 鏈表尾節點
// 鏈表節點類
private static class Node<T> {
private T data; // 節點數據
private Node<T> prev; // 前一個節點引用
private Node<T> next; // 后一個節點引用
public Node(T data) {
this.data = data;
}
}
// 在鏈表末尾添加節點
public void add(T data) {
Node<T> newNode = new Node<>(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
}
// 在鏈表指定位置插入節點
public void insert(int index, T data) {
if (index < 0 || index > size()) {
throw new IndexOutOfBoundsException();
}
Node<T> newNode = new Node<>(data);
if (index == 0) {
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
} else if (index == size()) {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
} else {
Node<T> current = getNode(index);
newNode.prev = current.prev;
newNode.next = current;
current.prev.next = newNode;
current.prev = newNode;
}
}
// 獲取鏈表指定位置的節點
private Node<T> getNode(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException();
}
Node<T> current = head;
for (int i = 0; i < index; i++) {
current = current.next;
}
return current;
}
// 移除鏈表指定位置的節點
public void remove(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException();
}
if (index == 0) {
head = head.next;
if (head == null) {
tail = null;
} else {
head.prev = null;
}
} else if (index == size() - 1) {
tail = tail.prev;
tail.next = null;
} else {
Node<T> current = getNode(index);
current.prev.next = current.next;
current.next.prev = current.prev;
}
}
// 獲取鏈表大小
public int size() {
int count = 0;
Node<T> current = head;
while (current != null) {
count++;
current = current.next;
}
return count;
}
}
以上是一個簡單的雙向鏈表類的實現示例,你可以使用該類來創建雙向鏈表并進行插入、移除、獲取節點等操作。