java 实现双向链表
时间: 2024-04-09 20:12:47 浏览: 65
双向链表是一种数据结构,每个节点包含了指向前一个节点和后一个节点的指针。在 Java 中,可以使用自定义类来实现双向链表。以下是一个简单的双向链表的实现示例:
```java
public class DoublyLinkedList {
private Node head;
private Node tail;
private class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
public void addToFront(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 addToBack(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
tail.next = newNode;
newNode.prev = tail;
tail = newNode;
}
}
public void remove(int data) {
Node current = head;
while (current != null) {
if (current.data == data) {
if (current == head) {
head = current.next;
if (head != null) {
head.prev = null;
}
} else if (current == tail) {
tail = current.prev;
if (tail != null) {
tail.next = null;
}
} else {
current.prev.next = current.next;
current.next.prev = current.prev;
}
break;
}
current = current.next;
}
}
public void printList() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
```
以上代码中的 `DoublyLinkedList` 类实现了双向链表的常见操作,如在头部和尾部添加节点、删除指定节点以及打印链表。你可以创建 `DoublyLinkedList` 对象并调用相应的方法来操作双向链表。
阅读全文