2022-11-24 18:04:38 +00:00
|
|
|
'''
|
|
|
|
File: array_stack.py
|
2022-11-29 13:42:59 +00:00
|
|
|
Created Time: 2022-11-29
|
|
|
|
Author: Peng Chen (pengchzn@gmail.com)
|
2022-11-24 18:04:38 +00:00
|
|
|
'''
|
|
|
|
|
2022-11-29 15:35:51 +00:00
|
|
|
import sys, os.path as osp
|
2022-11-24 18:04:38 +00:00
|
|
|
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
|
|
|
from include import *
|
|
|
|
|
2022-11-29 05:58:23 +00:00
|
|
|
""" 基于数组实现的栈 """
|
|
|
|
class ArrayStack:
|
|
|
|
def __init__(self):
|
2022-11-29 15:35:51 +00:00
|
|
|
self.__stack = []
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 获取栈的长度 """
|
|
|
|
def size(self):
|
2022-11-29 15:35:51 +00:00
|
|
|
return len(self.__stack)
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 判断栈是否为空 """
|
2022-11-29 14:58:16 +00:00
|
|
|
def is_empty(self):
|
2022-11-29 15:35:51 +00:00
|
|
|
return self.__stack == []
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 入栈 """
|
|
|
|
def push(self, item):
|
2022-11-29 15:35:51 +00:00
|
|
|
self.__stack.append(item)
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 出栈 """
|
|
|
|
def pop(self):
|
2022-11-29 15:35:51 +00:00
|
|
|
return self.__stack.pop()
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 访问栈顶元素 """
|
|
|
|
def peek(self):
|
2022-11-29 15:35:51 +00:00
|
|
|
return self.__stack[-1]
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 访问索引 index 处元素 """
|
|
|
|
def get(self, index):
|
2022-11-29 15:35:51 +00:00
|
|
|
return self.__stack[index]
|
|
|
|
|
|
|
|
""" 返回列表用于打印 """
|
2022-11-29 18:27:26 +00:00
|
|
|
def to_list(self):
|
2022-11-29 15:35:51 +00:00
|
|
|
return self.__stack
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
|
2022-11-29 15:35:51 +00:00
|
|
|
""" Driver Code """
|
2022-11-29 05:58:23 +00:00
|
|
|
if __name__ == "__main__":
|
|
|
|
""" 初始化栈 """
|
|
|
|
stack = ArrayStack()
|
|
|
|
|
|
|
|
""" 元素入栈 """
|
|
|
|
stack.push(1)
|
|
|
|
stack.push(3)
|
|
|
|
stack.push(2)
|
|
|
|
stack.push(5)
|
|
|
|
stack.push(4)
|
2022-11-29 18:27:26 +00:00
|
|
|
print("栈 stack =", stack.to_list())
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 访问栈顶元素 """
|
|
|
|
peek = stack.peek()
|
2022-11-29 15:35:51 +00:00
|
|
|
print("栈顶元素 peek =", peek)
|
2022-11-29 05:58:23 +00:00
|
|
|
|
2022-11-29 19:46:53 +00:00
|
|
|
""" 访问索引 index 处元素 """
|
2022-11-30 22:50:25 +00:00
|
|
|
num = stack.get(3)
|
|
|
|
print("栈索引 3 处的元素为 num =", num)
|
2022-11-29 19:46:53 +00:00
|
|
|
|
2022-11-29 05:58:23 +00:00
|
|
|
""" 元素出栈 """
|
|
|
|
pop = stack.pop()
|
2022-11-29 15:35:51 +00:00
|
|
|
print("出栈元素 pop =", pop)
|
2022-11-29 18:27:26 +00:00
|
|
|
print("出栈后 stack =", stack.to_list())
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 获取栈的长度 """
|
|
|
|
size = stack.size()
|
2022-11-29 15:35:51 +00:00
|
|
|
print("栈的长度 size =", size)
|
2022-11-29 05:58:23 +00:00
|
|
|
|
|
|
|
""" 判断是否为空 """
|
2022-11-29 18:27:26 +00:00
|
|
|
is_empty = stack.is_empty()
|
2022-11-30 22:50:25 +00:00
|
|
|
print("栈是否为空 =", is_empty)
|