实现Java中的双向链表数据结构方法
发布时间:2023-07-06 11:49:33
双向链表是一种常见的数据结构,它可以在每个节点中保存前驱节点和后继节点的指针,使得可以双向遍历链表。在Java中,可以通过自定义类实现双向链表。
首先,我们需要定义一个表示节点的类,包含两个属性:数据和前驱节点和后继节点的指针。
class Node<T> {
T data;
Node<T> prev;
Node<T> next;
public Node(T data) {
this.data = data;
this.prev = null;
this.next = null;
}
}
接下来,我们定义双向链表类,包含以下方法:
1. 头插法插入节点:在链表头部插入一个新节点。
public void insertFirst(T data) {
Node<T> newNode = new Node<>(data);
if (head == null) {
head = newNode;
tail = newNode;
} else {
newNode.next = head;
head.prev = newNode;
head = newNode;
}
}
2. 尾插法插入节点:在链表尾部插入一个新节点。
public void insertLast(T data) {
Node<T> newNode = new Node<>(data);
if (tail == null) {
head = newNode;
tail = newNode;
} else {
newNode.prev = tail;
tail.next = newNode;
tail = newNode;
}
}
3. 删除指定节点:删除链表中指定节点。
public void delete(T data) {
Node<T> 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 = tail.prev;
if (tail != null) {
tail.next = null;
}
} else {
current.prev.next = current.next;
current.next.prev = current.prev;
}
return;
}
current = current.next;
}
}
4. 遍历节点:遍历链表中的所有节点。
public void printList() {
Node<T> current = head;
while (current != null) {
System.out.print(current.data + " ");
current = current.next;
}
System.out.println();
}
5. 反向遍历节点:从链表尾部开始向前遍历所有节点。
public void printReverseList() {
Node<T> current = tail;
while (current != null) {
System.out.print(current.data + " ");
current = current.prev;
}
System.out.println();
}
这样,我们就完成了双向链表的实现。可以通过下面的代码进行测试:
public class DoublyLinkedListDemo {
public static void main(String[] args) {
DoublyLinkedList<Integer> list = new DoublyLinkedList<>();
list.insertFirst(3);
list.insertFirst(5);
list.insertLast(2);
list.insertLast(7);
list.delete(5);
list.printList(); // 输出:3 2 7
list.printReverseList(); // 输出:7 2 3
}
}
通过上述代码,我们可以看到双向链表的基本操作方法的实现,可以根据自己的需要进行扩展和实现其他功能。
