-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy patharray_stack.py
More file actions
39 lines (30 loc) · 823 Bytes
/
array_stack.py
File metadata and controls
39 lines (30 loc) · 823 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# 使用数组实现的栈
class ArrayStack:
def __init__(self, capacity: int):
self.data = []
self.size = 0
self.capacity = capacity
# 入栈
def push(self, val: int):
if self.size >= self.capacity:
raise RuntimeError('the stack is full')
self.data.append(val)
self.size += 1
# 出栈
def pop(self) -> int:
if self.size <= 0:
raise RuntimeError('the stack is empty')
res = self.data[self.size - 1]
self.data = self.data[:self.size - 1]
self.size -= 1
return res
if __name__ == '__main__':
stack = ArrayStack(10)
stack.push(1)
stack.push(6)
stack.push(3)
print(stack.pop())
print(stack.pop())
print(stack.pop())
stack.push(10)
print(stack.pop())