JAVA 双向链表
时间: 2024-02-15 11:57:52 浏览: 70
Java实现双向链表
在Java中实现双向链表需要定义一个节点类,节点类中包含一个数据项和两个指针,分别指向前一个节点和后一个节点。下面是一个简单的Java代码示例:
```java
class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
class DoublyLinkedList {
Node head;
public DoublyLinkedList() {
this.head = null;
}
// 在链表头部插入一个节点
public void insertAtHead(int data) {
Node newNode = new Node(data);
newNode.next = head;
if (head != null) {
head.prev = newNode;
}
head = newNode;
}
// 在链表尾部插入一个节点
public void insertAtTail(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
return;
}
Node current = head;
while (current.next != null) {
current = current.next;
}
current.next = newNode;
newNode.prev = current;
}
// 在指定位置插入一个节点
public void insertAtPosition(int data, int position) {
Node newNode = new Node(data);
if (head == null || position == 1) {
newNode.next = head;
if (head != null) {
head.prev = newNode;
}
head = newNode;
return;
}
Node current = head;
int currentPosition = 1;
while (currentPosition < position - 1 && current.next != null) {
current = current.next;
currentPosition++;
}
newNode.next = current.next; newNode.prev = current;
current.next = newNode;
if (newNode.next != null) {
newNode.next.prev = newNode;
}
}
// 从链表中删除一个节点
public void deleteNode(int data) {
if (head == null) {
return;
}
Node current = head;
while (current != null) {
if (current.data == data) {
if (current.prev != null) {
current.prev.next = current.next;
} else {
head = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
}
return;
}
current = current.next;
}
}
// 输出链表中的所有节点
public void display() {
Node current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
}
```
然后可以通过以下方式进行测试:
```java
public class Main {
public static void main(String[] args) {
DoublyLinkedList list = new DoublyLinkedList();
list.insertAtHead(3);
list.insertAtHead(2);
list.insertAtHead(1);
list.insertAtTail(4);
list.insertAtTail(5);
list.insertAtPosition(6, 3);
list.display(); // 输出:1 2 6 3 4 5
list.deleteNode(3);
list.display(); // 输出:1 2 6 4 5
}
}
```
阅读全文