删除链表中的最后一个节点

时间:2021-07-19 12:31:00

标签: python python-3.x data-structures linked-list

我正在使用 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

我的疑问是为什么最后一个节点没有被删除。另外,当最后一个节点已经设置为 30 时,它如何打印值 temp = None

2 个答案:

答案 0 :(得分:1)

嗯,你的链表是:

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 指向真实头节点的虚拟头节点。

答案 1 :(得分:0)

display: inline
相关问题