我正在尝试编写代码来删除循环链表中的最后一个元素,但我不知道我是否做错了什么。
我已经尝试了许多类似代码的参考,但我的如图所示将无法运行。请告诉我我哪里做错了。
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
发生这种情况是因为您正在重写 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