用 push 方法实现栈
在上一段视频中,您学习了如何在 Python 中实现栈。正如所见,栈遵循 LIFO 原则:最后入栈的元素最先出栈。
本练习分两步,使用单向链表实现带有 push() 操作的栈。您还将定义一个名为 size 的新属性,用于记录栈中元素的数量。您将先编写类来构建一个 Stack(),随后实现 push() 操作。
为此,您将使用如下代码的 Node() 类:
class Node:
def __init__(self, data):
self.data = data
self.next = None
本练习是课程的一部分
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 = ____