链接列表问题

如何保持链表的排序?如果超过10个项目,我该如何删除?

选择 | 换行 | 行号
  1. from node import node
  2.  
  3. probe = head
  4. count = 0
  5. while probe != None:
  6.     count += 1
  7.     probe = probe.next
  8. return count
  9.  
  10. def insert(newName, newScore, head):
  11.     probe.next.score = newScore
  12.     if head is None:
  13.         head = newNode
  14.     else:
  15.         probe = head
  16.         while probe.next != None:
  17.                 probe = probe.next
  18.                 probe.next = newNode
  19.     return head
  20.  
  21. def printStructure(newName, newScore):
  22.     probe = head
  23.     while probe != None:
  24.         print "Name: ", probe.name,
  25.         print "Score: ", probe.score
  26.         probe = probe.next
  27.  
  28. def main():
  29.     head  = None
  30.  
  31.     head = insert("She-RA", 1088, head)
  32.     printStructure(head)
  33.  
  34.     #Add ten nodes to the beginning of the linked structure
  35.     head = insert("He-MAN", 32464, head)
  36.     head = insert("Doc-Ock", 143322, head)
  37.     head = insert("Spidey", 6416, head)
  38.     head = insert("Superman", 63438, head)
  39.     head = insert("Arceus", 92515, head)
  40.     head = insert("Batman", 11986, head)
  41.     head = insert("Homer", 26712, head)
  42.     head = insert("F-ZERO", 833849, head)
  43.     insert("Dlew58", 999999, head)
  44.     print "Top Ten"
  45.     printStructure(head)
  46. if __name__ == "__main__":
  47.     main()
  48.  
# 回答1


链表不是排序的,它是按某种顺序链接的。因此,如果在链表中有值为'A'、'C'、'E'、'G'、'H'的记录,并且您想要添加'B',则下一个记录号将是6,因此记录号1将指向6而不是2,并且记录6将指向第二个记录以保持它们的顺序。
这取决于您谈论的是内存还是磁盘上的文件。通常,您将其标记为已删除,然后简单地删除指向它的链接,这样指向它的记录就会指向它曾经指向的记录。实际上,并不是每次删除记录时都需要重新生成链表,而是在达到某个阈值后重新生成链表。要重新生成链表,应将原始列表中的记录复制到新的内存位置或文件,而不复制已删除的记录。

标签: python

添加新评论