双链表java数据结构代码
时间: 2024-10-28 09:04:06 浏览: 29
双链表是一种动态数据结构,在Java中通常通过定义两个节点引用(一个是前驱节点,一个是后继节点)来实现。以下是简单的单向双链表节点和链表类的示例代码:
```java
// 双链表节点定义
class Node {
int data;
Node prev;
Node next;
public Node(int data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
// 双链表类定义
public class DoublyLinkedList {
private Node head; // 链表头节点
private Node tail; // 链表尾节点
// 添加元素到链表尾部
public void append(int data) {
Node newNode = new Node(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
}
// 删除指定位置的节点
public void delete(int index) {
if (index < 0 || index >= size()) return;
Node current = head;
for (int i = 0; i < index && current != null; i++) {
current = current.next;
}
if (current == null) return;
if (current.prev != null) {
current.prev.next = current.next;
} else { // 如果删除的是头节点
head = current.next;
}
if (current.next != null) {
current.next.prev = current.prev;
} else { // 如果删除的是尾节点
tail = current.prev;
}
}
// 获取链表长度
private int size() {
int count = 0;
Node temp = head;
while (temp != null) {
count++;
temp = temp.next;
}
return count;
}
// 其他辅助方法,如遍历、查找等...
}
```
阅读全文