為堆疊實作 pop 方法
在這個練習中,你要為堆疊實作 pop() 操作。pop() 會用來從堆疊頂端移除一個元素。我們同樣會使用 size 屬性來判斷堆疊中的元素數量。
回顧 Node() 類別:
class Node:
def __init__(self, data):
self.data = data
self.next = None
本練習屬於課程
Data Structures and Algorithms in Python
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class Stack:
def __init__(self):
self.top = None
self.size = 0
def pop(self):
# Check if there is a top element
if self.____ is None:
return None
else:
popped_node = self.top
# Decrement the size of the stack
self.size -= ____
# Update the new value for the top node
self.top = self.____
popped_node.next = None
return popped_node.data