python - 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?
解决方案
如评论中所述,您正在以非常类似于 C 的方式处理您的问题,而您应该使用标准库。
但不管怎样,您的代码的问题在于,当您添加一个 itemx
并且一个条目x
位于您的列表末尾时current.next_node
is时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)
推荐阅读
- google-chrome - 有没有办法将消息附加到网页上的电报链接的 tg:// 处理程序 url?
- css - 对话框中的双滚动条
- android - 让 Kotlin Serializer 与 Retrofit 一起工作
- c - 关于缺少原型错误的说明
- javascript - 我可以使用 Tensorflow.js 进行无监督学习吗?
- javascript - 在 youtube iframe 中隐藏相关视频
- php - 尝试连接到 Azure SQL 服务器时,我得到一个 PDOException 找不到驱动程序
- html - 如何控制 div 和 svg 的位置
- wpf - XAML WPF 中 {x:Static} 和 {StaticResource} 之间的区别
- css - 从另一个元素引用元素元素选择器