Java中的雙向鏈表可以通過定義一個Node類來實現,該類包含一個值和兩個指針,分別指向前一個節點和后一個節點。具體實現如下:
public class DoublyLinkedList {
private Node head; // 鏈表頭節點
private Node tail; // 鏈表尾節點
// 節點類
private class Node {
private int value;
private Node prev;
private Node next;
public Node(int value) {
this.value = value;
this.prev = null;
this.next = null;
}
}
// 在鏈表末尾添加節點
public void add(int value) {
Node newNode = new Node(value);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
}
// 在指定位置插入節點
public void insert(int index, int value) {
if (index < 0 || index > size()) {
throw new IndexOutOfBoundsException("Invalid index");
}
if (index == 0) {
Node newNode = new Node(value);
newNode.next = head;
head.prev = newNode;
head = newNode;
} else if (index == size()) {
add(value);
} else {
Node cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
Node newNode = new Node(value);
newNode.prev = cur.prev;
newNode.next = cur;
cur.prev.next = newNode;
cur.prev = newNode;
}
}
// 刪除指定位置的節點
public void remove(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("Invalid index");
}
if (index == 0) {
head = head.next;
head.prev = null;
} else if (index == size() - 1) {
tail = tail.prev;
tail.next = null;
} else {
Node cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
cur.prev.next = cur.next;
cur.next.prev = cur.prev;
}
}
// 獲取指定位置的節點值
public int get(int index) {
if (index < 0 || index >= size()) {
throw new IndexOutOfBoundsException("Invalid index");
}
Node cur = head;
for (int i = 0; i < index; i++) {
cur = cur.next;
}
return cur.value;
}
// 返回鏈表的大小
public int size() {
int count = 0;
Node cur = head;
while (cur != null) {
count++;
cur = cur.next;
}
return count;
}
}
使用示例:
public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.add(1);
list.add(2);
list.add(3);
System.out.println("Size: " + list.size()); // 輸出:Size: 3
list.insert(1, 4);
System.out.println("Size: " + list.size()); // 輸出:Size: 4
System.out.println("Element at index 1: " + list.get(1)); // 輸出:Element at index 1: 4
list.remove(2);
System.out.println("Size: " + list.size()); // 輸出:Size: 3
System.out.println("Element at index 2: " + list.get(2)); // 輸出:Element at index 2: 3
}
}
以上代碼實現了一個簡單的雙向鏈表,并提供了添加、插入、刪除和獲取節點的功能。