当我运行代码时,在附加值9之后,它将继续停止(冻结)。在手动终止它并查看失败的地方之后。我还是不太明白。
该程序应能处理来自对象的列表。我使用了一个类List en和一个类Node。节点是帮助类。
任何见解都会非常感谢!
class List:
class Node:
""" Een node bevat een value (val) en een next-ptr (lnk) """
def __init__(self, val, lnk=None):
self.val = val
self.lnk = lnk
def __init__(self):
self.root = None
def toon(self):
""" returns a string containing de elements-value of list.
The order is de order in the list, values are seperated buy ","
and enclosed by "[" and "]".
An example "[een,twee,zes]".
"""
string = "["
printval = self.root
while printval is not None:
string += printval.val
printval = printval.lnk
string += "]"
return string
def append(self, val):
""" Appends a node with value `val` to the end of the list.
"""
node = self.Node(val)
cur = self.root
while cur.lnk != None:
cur = cur.lnk
cur.lnk = node
def insert(self, val):
""" Inserts a node with value `val` to the beginning of the list.
"""
self.root = self.Node(val)
def addSorted(self, val):
""" Add a node with value `val` to list.
It's place is based on value `val`.
All the items in de list are sorted on their value'
An example: We have "[een,zes]"
Adding "twee" will give "[een,twee,zes]"
To work well the list must be in order.
"""
head = self.root
# check if list is empty
if head is None:
node = self.Node(val)
self.root = node
return
else:
while head.lnk != None:
# check if the value of root is greater than value
if head.val > val:
node = self.Node(val)
node.lnk = head
self.root = node
# if value smaller is than root value
else:
node = self.Node(val)
node.lnk = head.lnk
head.next = node
return
def delete(self, val):
""" Verwijder the node with value `val` from the list.
"""
head = self.root
while head is not None:
if head.val == val:
head.val = None
head = head.lnk
if __name__ == '__main__':
lst = List() ; print(lst.toon())
lst.insert("1") ; print(lst.toon())
lst.insert("0") ; print(lst.toon())
lst.addSorted("5") ; print(lst.toon())
lst.addSorted("3") ; print(lst.toon())
lst.addSorted("7") ; print(lst.toon())
lst.addSorted("4") ; print(lst.toon())
lst.append("8") ; print(lst.toon())
lst.append("9") ; print(lst.toon())
lst.addSorted("2") ; print(lst.toon())
lst.delete("2") ; print(lst.toon())
lst.delete("7") ; print(lst.toon())
lst.delete("9") ; print(lst.toon())
lst.delete("0") ; print(lst.toon())
lst.delete("11") ; print(lst.toon())
lst.append("9") ; print(lst.toon())