15、Java数据结构与算法——数据结构篇之线性表3

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的全部内容,作者能力有限,如果不足请及时指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值