数据结构-栈
栈是一种后进先出的数据结构 ,栈满时不能入栈,栈空时不能出栈。
python代码实现:
class Stack(object): def __init__(self, limit=10): self.stack = [] #存放元素 self.limit = limit #栈容量极限 def push(self, data): #入栈 if len(self.stack) >= self.limit: print(‘StackOverflowError‘) self.stack.append(data) def pop(self):#出栈 if self.stack: return self.stack.pop() else: raise IndexError(‘pop from an empty stack‘) #空栈不能被弹出 def peek(self): #查看堆栈的最上面的元素 if self.stack: return self.stack[-1] def is_empty(self): #判断栈是否为空 return not bool(self.stack) def size(self): #返回栈的大小 return len(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]
True 0 [2] False 3 [2] [3]
相关推荐
koushr 2020-11-12
zhangxiafll 2020-11-13
kikaylee 2020-10-31
范范 2020-10-28
MILemon 2020-10-22
hugebawu 2020-10-12
LauraRan 2020-09-28
shenwenjie 2020-09-24
omyrobin 2020-09-23
guangcheng 2020-09-22
qiangde 2020-09-13
hanyujianke 2020-08-18
晨曦之星 2020-08-14
xiesheng 2020-08-06
KAIrving 2020-08-02
xiesheng 2020-08-02
范范 2020-07-30
chenfei0 2020-07-30