问。在循环链表的开头插入新节点的程序。

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

说明

在本程序中,我们将创建一个循环链表,并将每个新节点插入到链表的开头。如果链表为空,则 head 和 tail 都将指向新添加的节点。如果链表不为空,我们将把 head 的数据存储在一个临时节点 temp 中,并将新节点设为 head。这个新的 head 将指向临时节点。简单来说,新添加的节点将成为第一个节点(head),而之前的 head(temp)将成为链表的第二个节点。

Program to insert a new node at the beginning of the circular linked list

在列表开头插入新节点后

Program to insert a new node at the beginning of the circular linked list

New 代表新添加的节点。之前 A 是链表的 head。当 New 被添加到链表开头时,New 将成为新的 head,并指向之前的 head,即 A。

算法

  1. 定义一个 Node 类,它表示列表中的一个节点。它有两个属性 data 和 next,next 将指向下一个节点。
  2. 定义另一个类来创建循环链表,它有两个节点:head 和 tail。它有两个方法:addAtStart() 和 display() 。
  3. addAtStart() 将节点添加到链表开头。
    1. 它首先检查 head 是否为 null(空列表),然后它将节点插入为 head。
    2. head 和 tail 都将指向新添加的节点。
    3. 如果列表不为空,则新添加的节点将成为新的头节点,它将指向之前的头节点。
  4. display() 将显示列表中存在的所有节点。
    1. 定义一个新节点“current”,它将指向头节点。
    2. 打印 current.data 直到 current 再次指向 head。
    3. 在每次迭代中,current 将指向列表中的下一个节点。

解决方案

Python

输出

Adding nodes to the start of the list: 
1
Adding nodes to the start of the list: 
2 1
Adding nodes to the start of the list: 
3 2 1
Adding nodes to the start of the list: 
4 3 2 1

C

输出

Adding nodes to the start of the list: 
1
Adding nodes to the start of the list: 
2 1
Adding nodes to the start of the list: 
3 2 1
Adding nodes to the start of the list: 
4 3 2 1

JAVA

输出

Adding nodes to the start of the list: 
1
Adding nodes to the start of the list: 
2 1
Adding nodes to the start of the list: 
3 2 1
Adding nodes to the start of the list: 
4 3 2 1

C#

输出

 Adding nodes to the start of the list: 
1
Adding nodes to the start of the list: 
2 1
Adding nodes to the start of the list: 
3 2 1
Adding nodes to the start of the list: 
4 3 2 1

PHP

输出

Adding nodes to the start of the list: 
1
Adding nodes to the start of the list: 
2 1
Adding nodes to the start of the list: 
3 2 1
Adding nodes to the start of the list: 
4 3 2 1
 
下一主题#