用 push 方法實作 Stack
在上一支影片中,你學到如何在 Python 中實作堆疊(stack)。如同你所見,堆疊遵循 LIFO 原則:最後插入的元素會最先取出。
在這個練習中,你會用兩個步驟,利用單向鏈結串列(singly linked list)實作支援 push() 操作的堆疊。你也會定義一個名為 size 的新屬性,用來追蹤堆疊中的項目數量。你會先撰寫類別來建立 Stack(),接著實作 push() 操作。
為了完成這個程式,你會使用 Node() 類別,其程式碼如下:
class Node:
def __init__(self, data):
self.data = data
self.next = None
本練習屬於課程
Data Structures and Algorithms in Python
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
class Stack:
def __init__(self):
# Initially there won't be any node at the top of the stack
____
# Initially there will be zero elements in the stack
self.size = ____