Python 数据结构之数组栈的建立
1.栈:一种限制性的线性顺序结构,通过栈顶(top)实现增删。
2.栈的5种基本操作:
初始化、压栈、出栈、判断空、判断满
- 初始化
Stack_Size = 10
top = -1
bottom = -1
arr_stack = [] * Stack_Size
- 压栈
def push(value):
global top
if top <= Stack_Size - 1:
arr_stack.append(value)
top += 1
else:
print("空间已满!")
print(arr_stack)
- 出栈
def pop():
global top
if is_Empty():
print("空间以清空!")
else:
top -= 1
return arr_stack.pop()
- 判断空
def is_Empty():
global top
if top == bottom:
return True
else:
return False
- 判断满
def is_full():
global top
if top == Stack_Size - 1:
return True
else:
return False
总结代码
Stack_Size = 10
top = -1
bottom = -1
arr_stack = [] * Stack_Size
def is_Empty():
global top
if top == bottom:
return True
else:
return False
def is_full():
global top
if top == Stack_Size - 1:
return True
else:
return False
def push(value):
global top
if top <= Stack_Size - 1:
arr_stack.append(value)
top += 1
else:
print("空间已满!")
print(arr_stack)
def pop():
global top
if is_Empty():
print("空间以清空!")
else:
top -= 1
return arr_stack.pop()
if __name__ == '__main__':
print(is_Empty())
print(is_full())
for i in range(10):
push(i)
print(is_Empty())
print(is_full())