要使用Node类和链接列表类删除列表中的最后一个元素,可以按照以下步骤进行操作:
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def delete_last(self):
if self.head is None:
return
elif self.head.next is None:
self.head = None
else:
current = self.head
while current.next.next:
current = current.next
current.next = None
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
return elements
my_list = LinkedList()
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)
my_list.delete_last()
print(my_list.display()) # 输出 [1, 2, 3]
这样,就使用Node类和链接列表类成功删除了列表中的最后一个元素。
领取专属 10元无门槛券
手把手带您无忧上云