Linked list questions

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Derrick Lewis
    New Member
    • Dec 2010
    • 1

    Linked list questions

    How do i keep a linked list sorted? How do i remove if more than 10 items?

    Code:
    from node import node
    
    probe = head
    count = 0
    while probe != None:
        count += 1
        probe = probe.next
    return count
           
    def insert(newName, newScore, head):
        probe.next.score = newScore
        if head is None:
            head = newNode
        else:
            probe = head
            while probe.next != None:
                    probe = probe.next
                    probe.next = newNode
        return head
    
    def printStructure(newName, newScore):
        probe = head
        while probe != None:
            print "Name: ", probe.name,
            print "Score: ", probe.score
            probe = probe.next
    
    def main():
        head  = None
    
        head = insert("She-RA", 1088, head)
        printStructure(head)
    
        #Add ten nodes to the beginning of the linked structure
        head = insert("He-MAN", 32464, head)
        head = insert("Doc-Ock", 143322, head)
        head = insert("Spidey", 6416, head)
        head = insert("Superman", 63438, head)
        head = insert("Arceus", 92515, head)
        head = insert("Batman", 11986, head)
        head = insert("Homer", 26712, head)
        head = insert("F-ZERO", 833849, head)
        insert("Dlew58", 999999, head)
        print "Top Ten"
        printStructure(head)
    if __name__ == "__main__":
        main()
    Last edited by bvdet; Dec 20 '10, 10:41 PM. Reason: Fix code tags, ask question , add appropriate title
  • dwblas
    Recognized Expert Contributor
    • May 2008
    • 626

    #2
    A linked list is not sorted, it is linked in some order. So if you have records with the values 'A', 'C', 'E', 'G', 'H' in the linked list and you wanted to add 'B', the next record number would then be 6, so record number 1 would point to 6 instead of 2, and record 6 would point to the second record to keep them in order.
    How do i remove if more than 10 items?
    It depends on if you are talking about memory or a file on disk. Generally you mark it as deleted, and simply remove the link to it, so the record that points to it would point to the record that it used to point to. Practically speaking, regenerating the linked list isn't necessary every time a record is deleted but is done after some threshold is reached. To regenerate the linked list, you would copy the records in the original list to a new memory location or file without copying the deleted records.

    Comment

    Working...