首页 > 解决方案 > Linked list creating a new node for an item that already exists in list

问题描述

I am adding nodes to the end of my linked list that is counting the frequencies of characters from a given file. However, my code doesn't seem to be iterating fully through the linked list as it creates a new node for a node that already exists in the list.

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)

A section of the output is shown below

  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

Why is the add function not counting the frequency of a node already in the list but creating a new node instead?

标签: python

解决方案


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

但不管怎样,您的代码的问题在于,当您添加一个 itemx并且一个条目x位于您的列表末尾时current.next_nodeis时None,您的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)

推荐阅读