创建包含 n 个节点的单向链表并计算节点数量的程序

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

说明

在此程序中,我们需要创建一个单向链表并计算列表中存在的节点数。

Program to create a singly linked list of n nodes and count the number of nodes

要完成此任务,请使用初始指向 head 的节点 current 遍历列表。以 such a way that current will point to its next node in each iteration and increment variable count by 1 的方式递增 current。最后,count 将保存表示列表中节点数的值。

算法

  1. 创建一个名为 Node 的类,它有两个属性:data 和 next。Next 是指向链表中下一个节点的指针。
  2. 创建另一个类,该类具有两个属性:head 和 tail。
  3. addNode() 将向列表添加一个新节点
    1. 创建一个新节点。
    2. 它首先检查 head 是否等于 null,这意味着列表为空。
    3. 如果列表为空,head 和 tail 都将指向新添加的节点。
    4. 如果列表不为空,新节点将添加到列表末尾,使得 tail 的 next 指向新添加的节点。此新节点将成为列表的新 tail。
  4. countNodes() 将计算列表中存在的节点数
    1. 定义一个节点 current,它最初将指向列表的 head。
    2. 声明并初始化变量 count 为 0。
    3. 遍历列表,直到 current 指向 null。
    4. 对于列表中遇到的每个节点,将 count 的值加 1。
  5. display() 将显示列表中存在的节点
    1. 定义一个节点 current,它最初将指向列表的 head。
    2. 遍历列表直到 current 指向 null。
    3. 通过使 current 在每次迭代中指向它的下一个节点来显示每个节点。

解决方案

Python

输出

 Nodes of singly linked list: 
1 2 3 4 
Count of nodes present in the list: 4

C

输出

Nodes of singly linked list: 
1 2 3 4 
Count of nodes present in the list: 4

JAVA

输出

Nodes of the singly linked list:
1 2 3 4 
Count of nodes present in the list: 4

C#

输出

Nodes of singly linked list: 
1 2 3 4 
Count of nodes present in the list: 4

PHP

输出

Nodes of singly linked list: 
1 2 3 4 
Count of nodes present in the list: 4
 
下一主题#