Java 在双向链表末尾插入新节点的程序

2025年3月17日 | 阅读 3 分钟

在此程式中,我們將建立一個雙向鏈結串列,並在串列的末端插入每一個新節點。如果串列是空的,則 head 和 tail 將指向新新增的節點。如果串列不是空的,則將新節點插入串列的末端,使得 tail 的 next 指向新節點。將新節點設為串列的新 tail,其 next 將指向 null。

Java program to insert a new node at the end of the Doubly Linked List

在上面的範例中,節點 4 是串列的 tail。現在,新節點將插入到串列的末端,使得節點 4 的 next 指向新節點。將新節點設為串列的 tail,其 next 將指向 null。

算法

  • 定义一个 Node 类,它表示列表中的一个节点。它将有三个属性:数据、previous 指向前一个节点,以及 next 指向下一个节点。
  • 定义另一个用于创建双向链表的类,它有两个节点:头节点和尾节点。最初,头节点和尾节点将指向 null。
  • addAtEnd() 將會將節點添加到串列中
    • 它首先检查头节点是否为 null,然后将节点作为头节点插入。
    • 头节点和尾节点都将指向新添加的节点。
    • 头节点的前一个指针将指向 null,尾节点的下一个指针将指向 null。
    • 如果头节点不为 null,则新节点将插入到列表的末尾,使得新节点的前一个指针将指向尾节点。
    • 新节点将成为新的尾节点。尾节点的下一个指针将指向 null。

a. display() 将显示列表中存在的所有节点。

  • 定义一个新节点“current”,它将指向头节点。
  • 打印 current.data 直到 current 指向 null。
  • 在每次迭代中,current 将指向列表中的下一个节点。

程序

输出

Adding a node to the end of the list: 
1 
Adding a node to the end of the list: 
1 2 
Adding a node to the end of the list: 
1 2 3 
Adding a node to the end of the list: 
1 2 3 4 
Adding a node to the end of the list: 
1 2 3 4 5 
下一个主题Java 程序