链表为lis中已存在的项目创建新节点

2024-03-29 15:03:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在向链表的末尾添加节点,该链表计算给定文件中字符的频率。但是,我的代码似乎没有完全遍历链表,因为它为链表中已经存在的节点创建了一个新节点

def add(self, new_item):
    if self.head == None:
        self.head  = FreqNode(new_item)
        return

    current = self.head

    while (current.next_node):
        if current.data == new_item:
            current.frequency += 1
            return
        current = current.next_node

    current.next_node = FreqNode(new_item)

输出的一部分如下所示

  20:  's' = 13341
  21:  's' = 1
  22:  'y' = 3461
  23:  'm' = 5441
  24:  'i' = 15916
  25:  'i' = 1
  26:  ',' = 3178
  27:  'w' = 3824
  28:  'd' = 6114
  29:  'v' = 1897
  30:  '.' = 1850
  31:  '.' = 1
  32:  '#' = 1
  33:  '*' = 27
  34:  '*' = 1
  35:  ''' = 112
  36:  'z' = 24
  37:  'x' = 386
  38:  'x' = 1
  39:  'q' = 193
  40:  'q' = 1
  41:  '?' = 88
  42:  '?' = 1

为什么add函数不计算列表中已有节点的频率,而是创建一个新节点


Tags: selfaddnodenewreturnif节点current
1条回答
网友
1楼 · 发布于 2024-03-29 15:03:04

如评论中所述,您正在以一种非常类似C的方式处理您的问题,而您应该使用标准库

但不管怎样,代码的问题是,当您添加一个项x,并且x的条目在列表的末尾时,current.next_nodeNone,您的while循环被跳过,并且您正在为同一项添加一个新节点。之后,计数被添加到第一个节点,留下一对(x, ...), (x, 1)。为了避免这种情况,你可以这样做

while True:
    if current.data == new_item:
        current.frequency += 1
        return
    if current.next_node is None:
        break
    current = current.next_node

current.next_node = FreqNode(new_item)

相关问题 更多 >