简体   繁体   中英

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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