使用链表查找数字的频率。
运行以下代码时,获取SIGTSTP-时限超出错误。谁能帮助我我在哪里弄错了?
class Element(object):
def __init__(self,value):
self.value = value
self.next = None
class LinkedList(object):
def __init__(self, head = None):
self.head = head
def append(self, new):
current = self.head
if self.head:
while current.next:
current = current.next
current.next = new
else:
self.head = new
def traverse(self):
current = self.head
while current != None:
print(current.value)
current = current.next
arr = list(map(int, input().split()))
ll = LinkedList()
for i in arr:
e = Element(i)
ll.append(e)
ll.traverse()
def frequency(a):
current = a.head
while current != None:
count = 1
while current.next != None:
if current.value == current.next.value:
current+=1
if current.next.next != None:
current.next = current.next.next
else:
current.next = None
print(str(current.value)+" : " + str(count))
current = current.next
frequency(ll)
答案 0 :(得分:0)
除频率外,其他一切看起来都不错。您将需要保留两个引用,一个引用到当前元素,另一个引用将从当前开始遍历列表的其余部分。那给你一些东西继续吗?
也请注意,当前的实现将修改基础链表,尽管您确实可以使用指针进行“跳过”以防止多次列出相同的元素,但最好避免以这种方式修改基础结构。