Java 在循环链表末尾插入新节点的程序

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

在此程序中,我们将创建一个循环链表,并将每个新节点插入到列表的末尾。如果列表为空,则 head 和 tail 将指向新添加的节点。如果列表不为空,新添加的节点将成为列表的新尾部。前一个尾部将新节点指向其下一个节点。由于这是一个循环链表;新的尾部将指向头部。换句话说,新节点将成为列表的最后一个节点(尾部),而前一个尾部将成为倒数第二个节点。

单位矩阵

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

将新节点插入到列表末尾后

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

New 代表新添加的节点。D 是前一个尾部。当 new 被添加到列表末尾时,它将成为新的尾部,D 将指向 new。

算法

  • 定义一个 Node 类,它表示列表中的一个节点。它有两个属性 data 和 next,next 将指向下一个节点。
  • 定义另一个类来创建循环链表,它有两个节点:head 和 tail。它有两个方法:addAtEnd() 和 display()。
  • addAtEnd() 将在列表末尾添加节点
    • 它首先检查 head 是否为 null(空列表),然后它将节点插入为 head。
    • head 和 tail 都将指向新添加的节点。
    • 如果列表不为空,则新添加的节点将成为新的尾部,而前一个尾部将新节点指向其下一个节点。新的尾部将指向头部。

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

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

程序

输出

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