hello-algo/codes/python/chapter_stack_and_queue/stack.py

42 lines
933 B
Python
Raw Normal View History

"""
File: stack.py
2022-11-29 21:42:59 +08:00
Created Time: 2022-11-29
Author: Peng Chen (pengchzn@gmail.com)
"""
2022-11-29 23:35:51 +08:00
import sys, os.path as osp
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
2023-03-03 03:07:22 +08:00
from modules import *
2022-11-29 23:35:51 +08:00
""" Driver Code """
2022-11-29 13:58:23 +08:00
if __name__ == "__main__":
""" 初始化栈 """
2022-11-29 23:35:51 +08:00
# Python 没有内置的栈类,可以把 list 当作栈来使用
2022-11-29 13:58:23 +08:00
stack = []
""" 元素入栈 """
stack.append(1)
stack.append(3)
stack.append(2)
stack.append(5)
stack.append(4)
2022-11-29 23:35:51 +08:00
print("栈 stack =", stack)
2022-11-29 13:58:23 +08:00
""" 访问栈顶元素 """
peek = stack[-1]
2022-11-29 23:35:51 +08:00
print("栈顶元素 peek =", peek)
2022-11-29 13:58:23 +08:00
""" 元素出栈 """
pop = stack.pop()
2022-11-29 23:35:51 +08:00
print("出栈元素 pop =", pop)
print("出栈后 stack =", stack)
2022-11-29 13:58:23 +08:00
""" 获取栈的长度 """
size = len(stack)
2022-11-29 23:35:51 +08:00
print("栈的长度 size =", size)
2022-11-29 13:58:23 +08:00
""" 判断是否为空 """
2022-11-30 02:27:26 +08:00
is_empty = len(stack) == 0
print("栈是否为空 =", is_empty)