1、双链表
双链表是一种更复杂的线性数据结构,它的每个节点都有两个链接,一个指向前一个节点,另一个指向后一个节点。这种结构允许我们从两个方向遍历列表。
public class Node {
int data;
Node prev;
Node next;
// Node constructor
public Node(int data) {
this.data = data;
}
}
2、双链表的初始化(带头结点)
在初始化一个带头结点的双链表时,我们创建一个没有数据的节点作为头结点。
public class DoublyLinkedList {
Node head;
// DoublyLinkedList constructor
public DoublyLinkedList() {
head = new Node(-1); // -1 or any value, since this is a dummy node
}
}
3、双链表的插入操作
插入操作可以在双链表的任何位置进行。这里我们实现在链表末尾添加一个新节点的方法:
public void append(int newData) {
Node newNode = new Node(newData);
Node last = head; // Start from the head
// If the list is not empty, go to the end of the list
while (last.next != null) {
last = last.next;
}
// Insert the new node at the end
last.next = newNode;
newNode.prev = last;
}
4、双链表的删除操作
删除操作也可以在双链表的任何位置进行。这里我们实现删除给定数据的第一个节点的方法:
public void deleteNode(int key) {
Node temp = head.next; // Start from the first node after head
// Find the node to be deleted
while (temp != null && temp.data != key) {
temp = temp.next;
}
// If the node is not found or the list is empty
if (temp == null) return;
// Unlink the node from the list
if (temp.next != null) {
temp.next.prev = temp.prev;
}
if (temp.prev != null) {
temp.prev.next = temp.next;
}
}
4、双链表的遍历操作
遍历操作可以从头到尾,也可以从尾到头。这里我们实现从头到尾的遍历:
public void printList() {
Node node = head.next; // Start from the first node after head
while (node != null) {
System.out.print(node.data + " ");
node = node.next;
}
System.out.println();
}
以上就是Java数据结构与算法——数据结构篇之线性表3的全部内容,作者能力有限,如果不足请及时指出。