You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何统计链表中的节点数?附问题代码及测试用例求助

修复LinkedList的节点统计及初始化问题

原代码存在的问题

  • 初始化逻辑混乱:__init__方法里嵌套了两层数组遍历,会导致重复创建节点;重复元素检查的逻辑错误,每次循环都触发检查,会多次打印提示,且位置不合理。
  • countNode方法完全错误:直接将self.head设为None,清空了链表,完全没实现节点计数的核心逻辑。
  • 缺少必要依赖:未定义Node类,也没实现测试用例里用到的printList方法,导致测试无法执行。

修复后的完整代码

class Node:
    def __init__(self, data, next_node=None):
        self.data = data
        self.next = next_node

class LinkedList:
    def __init__(self, a):
        self.head = None
        tail = None
        # 检查数组是否为空
        if len(a) == 0:
            print("Array is empty.")
            return
        # 检查元素是否唯一
        seen = set()
        has_duplicate = False
        for x in a:
            if x in seen:
                has_duplicate = True
                break
            seen.add(x)
        if has_duplicate:
            print("all keys are not unique")
        # 创建链表节点
        for x in a:
            new_node = Node(x)
            if self.head is None:
                self.head = new_node
                tail = new_node
            else:
                tail.next = new_node
                tail = new_node

    # 打印链表内容
    def printList(self):
        current = self.head
        elements = []
        while current is not None:
            elements.append(str(current.data))
            current = current.next
        print(",".join(elements))

    # 统计节点数量
    def countNode(self):
        count = 0
        current = self.head
        while current is not None:
            count += 1
            current = current.next
        return count

测试用例验证

print("////// Test 01 //////")
a1 = [10, 20, 30, 40]
h1 = LinkedList(a1) # Creates a linked list using the values from the array
# head will refer to the Node that contains the element from a[0]

h1.printList() # 输出: 10,20,30,40
print(h1.countNode()) # 输出: 4

关键修复说明

  1. 新增Node类:定义链表节点的基础结构,包含存储数据的data和指向下一节点的next属性。
  2. 重构初始化方法:
    • 拆分空数组检查、重复元素检查、节点创建三个逻辑,避免嵌套循环导致的错误。
    • 使用集合检查重复元素,效率更高且逻辑清晰。
  3. 实现printList方法:遍历链表收集所有节点数据,格式化输出符合测试用例要求的内容。
  4. 修复countNode方法:从链表头节点开始遍历,逐个计数,遍历完成后返回总数,不会修改原链表结构。

内容的提问来源于stack exchange,提问作者user15330159

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 08:50:25