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
}
}
以上代码实现了一个简单的双向链表,并提供了添加、插入、删除和获取节点的功能。