我正在使用Python实现链表中最后一个节点的删除。以下是我的代码:
class Node:
def __init__(self, key):
self.key = key
self.next = None
def printList(head):
curr = head
while curr != None:
print(curr.key, end=" ")
curr = curr.next
def deleteLastNode(head):
if head == None:
return None
temp = head
# Iterating till the last Node
while temp.next != None:
temp = temp.next
temp = None
return head
# Driver code
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head = deleteLastNode(head)
printList(head)
然而,在输出中,我仍然得到了完整的链表。
10 20 30
当最后一个节点已经设置为temp = None
时,如何打印30
?
好吧,你的链表是:
10 -> 20 -> 30
^head
您的迭代:
10 -> 20 -> 30
^head ^temp
那么当你做temp = None
时,就意味着(你只需将None
分配给temp
(:
10 -> 20 -> 30 None
^head ^temp
正确的方法是在20
上迭代时,执行temp.next = None
以删除对最后一个节点的引用。所以你的代码可能是:
class Node:
def __init__(self, key):
self.key = key
self.next = None
def printList(head):
curr = head
while curr != None:
print(curr.key, end=" ")
curr = curr.next
def deleteLastNode(head):
if head == None:
return None
temp = head
# Iterating till the last Node
while temp.next.next != None:
temp = temp.next
temp.next = None
return head
# Driver code
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head = deleteLastNode(head)
printList(head)
当您的链表至少包含两个元素时,此代码将起作用。当只有一个元素时,这将引发异常。我建议您使用next
指向真实头部节点的虚拟头部节点。
#Another way of solving
class Node:
def __init__(self, key):
self.key = key
self.next = None
def printList(head):
curr = head
while curr != None:
print(curr.key, end=" ")
curr = curr.next
def deleteLastNode(head):
if head == None:
return None
temp = head
prev=None #creating the value of previous element
# Iterating till the last Node
while temp.next != None:
prev=temp #updating for every iteration
temp = temp.next
prev.next = None #returning as NONE value
return head
# Driver code
head = Node(10)
head.next = Node(20)
head.next.next = Node(30)
head = deleteLastNode(head)
printList(head)