- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.py
More file actions
Latest commit
33 lines (33 loc) · 1.03 KB
/
Copy pathstack.py
File metadata and controls
33 lines (33 loc) · 1.03 KB
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
#-*-coding:utf-8-*-
classStack(object):
def__init__(self, limit=10):
self.stack= [] #存放元素
self.limit=limit#栈容量极限
defpush(self, data): #入栈
iflen(self.stack) >=self.limit:
print('StackOverflowError')
self.stack.append(data)
defpop(self):#出栈
ifself.stack:
returnself.stack.pop()
else:
raiseIndexError('pop from an empty stack') #空栈不能被弹出
defpeek(self): #查看堆栈的最上面的元素
ifself.stack:
returnself.stack[-1]
defis_empty(self): #判断栈是否为空
returnnotbool(self.stack)
defsize(self): #返回栈的大小
returnlen(self.stack)
if__name__=="__main__":
stack=Stack()
print(stack.is_empty())#True
print(stack.size())#0
stack.push([1])
stack.push([3])
stack.push([2])
print(stack.peek())#[2]
print(stack.is_empty())#False
print(stack.size())#3
print(stack.pop())#[2]
print(stack.peek())# [3]