【问题标题】:Find the frequency of numbers using linkedlist使用链表查找数字的频率
【发布时间】:2019-03-28 07:26:57
【问题描述】:

使用链表查找数字的频率。

在运行以下代码时获取 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)        

【问题讨论】:

  • 你为什么要在你的链接列表中添加你的项目的价值?
  • @FarhoodET 我将元素对象添加到链表

标签: python python-3.x linked-list


【解决方案1】:

一切看起来都很好,除了频率。您将需要保留两个引用,一个指向当前元素,另一个将从当前元素开始遍历列表的其余部分。这会让你有什么可做的吗?

还要注意,您当前的实现将修改底层链表,虽然您确实可以使用指针“跳过”以防止多次列出相同的元素,但最好避免以这种方式修改底层结构。

【讨论】:

    猜你喜欢
    • 2019-06-07
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 2010-09-13
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    相关资源
    最近更新 更多