我正在用Python写一个简单的链表代码,您能告诉我deleteT函数出什么问题了吗?它没有做好自己的工作
class SinglyLLNode(object):
def __init__(self,value):
self.value = value
self.next = None
class SinglyLL():
def __init__(self,value):
self.head=SinglyLLNode(value)
def getTail(self):
n=self.head
while n.next != None:
n = n.next
return n
def display(self):
n = self.head
a=[]
while n != None:
a.append(n.value)
n = n.next
print(*a,sep=" -> ")
def insertT(self,value):
n = self.getTail()
n.next=SinglyLLNode(value)
def deleteT(self):
n=self.head
if n is None:
print("Cant Delete Empty List")
return
elif n.next is None:
del n
return
else:
prev = n
while n.next is not None:
prev = n
n = n.next
prev.next = n
N = SinglyLL(100)
N.insertT(123)
N.insertT(1234)
N.display()
N.deleteT()
N.insertT(12345)
N.display()
输出为:
100-> 123-> 1234
100-> 123-> 1234-> 12345
但应该是 100-> 123-> 12345
PS:对不起,对大代码来说,请看其他人运行良好的deleteT()函数
答案 0 :(得分:1)
此deleteT
函数将删除链表的最后一个元素,确保新的最后一个元素指向None
:
def deleteT(self):
n=self.head
if n is None:
print("Cant Delete Empty List")
return
elif n.next is None:
del n
return
else:
while n.next.next is not None:
n = n.next
del n.next.next
n.next = None