删除循环链表最后一个节点的代码检查

问题描述 投票:0回答:1

我正在尝试编写代码来删除循环链表中的最后一个元素,但我不知道我是否做错了什么。

我已经尝试了许多类似代码的参考,但我的如图所示将无法运行。请告诉我我哪里做错了。

def del_end(self):
    if self.head is None:
        print("Cicular Linked List is empty")
    else:
        if self.head == self.tail:
            self.head = None
        else:
            a = self.head
            while a.next != self.tail:
                a = a.next
            self.tail = None
            self.tail = a
            a.next = self.head               
python linked-list
1个回答
0
投票

发生这种情况是因为您正在重写 self.tail 中的值,您的代码应该如下所示:

def del_end(self):
    if self.head is None:
        print("Circular Linked List is empty")
    else:
        if self.head == self.tail:
            self.head = None
            self.tail = None
        else:
            a= self.head
            while a.next != self.tail:
                a = a.next
            a.next = self.head
            self.tail = a
© www.soinside.com 2019 - 2024. All rights reserved.