简体   繁体   English

插入有序链接列表Python和总和重复项

[英]Insert into Ordered Linked List Python and Sum Duplicates

I am trying to insert item pairs (letter, frequency) into an ordered linked list. 我正在尝试将项目对(字母,频率)插入到有序链接列表中。 So far I am able to create the sorted linked list but I cannot figure out how to update the frequency and rearrange the list if a letter gets comes up twice. 到目前为止,我已经能够创建排序的链表,但是我无法弄清楚如果一个字母出现两次时如何更新频率并重新排列该表。

So far I have: 到目前为止,我有:

def add(self, letter, frequency):

    temp = Frequency(letter, frequency)

    curr = self.head
    prev = None
    stop = False

    while curr != None and not stop:
        if curr.frequency < temp.frequency:
            stop = True
        else:
            prev = curr
            curr = curr.next

    if prev == None:
        temp.set_next(self.head)
        self.head = temp
    else:
        temp.set_next(curr)
        prev.set_next(temp)

f = SortedFrequencyList()
f.add('a', 3)
f.add('b', 5)
f.add('g' 1)

returns 退货

({b: 5}, {a: 3}, {g: 1})

but if I were to do 但是如果我要做

f = SortedFrequencyList()
f.add('a', 3)
f.add('b', 5)
f.add('g', 1)
f.add('a', 3)

I get 我懂了

({b: 5}, {a: 3}, {a: 3}, {g: 1})

instead of 代替

({a: 6}, {b: 5}, {g: 1})

We can't do much in the way of coding help, since you haven't posted your support code: we don't have enough to reproduce the problem. 由于您尚未发布支持代码,因此我们无法在编码帮助方面做很多事情:我们没有足够的机会重现该问题。 You also haven't given us any coding attempt from which to work. 您也没有给我们任何编码尝试。

You need to build out more of your linked-list support. 您需要建立更多的链表支持。 So far, all you have is a method that inserts a new entry into the list. 到目前为止,您所拥有的只是一个将新条目插入列表的方法。 I recommend that you write a find method that locates an existing element by name (letter), and an update that will find it, increase the frequency, and sort it back into the list. 我建议您编写一个find方法,按名称(字母)查找一个现有元素,并进行更新以查找该元素,增加频率并将其排序回列表中。

The building-block way to do the update is to write a delete routine as well. 进行更新的基本方法是编写删除例程。 Find the item, hold a copy, delete it from the list, and then add a new one with the updated frequency. 找到该项目,持有一份副本,从列表中将删除 ,然后添加具有更新频率的新项目。

The nicer way to update is to do the removal and reinsertion in one routine, backing up the list. 更好的更新方法是在一个例程中进行删除和重新插入,以备份列表。 This suggests either a recursive memory or a doubly-linked list. 这表明递归内存或双向链表。 An even faster way is to implement some sort of indexed tree structure, so that the searches are faster. 甚至更快的方法是实现某种索引树结构,以便搜索更快。

Does this get you moving in the right direction? 这会使您朝正确的方向前进吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM