1. 程式人生 > >python中利用list實現stack

python中利用list實現stack


class mystack():
  def  __init__(self):
    self.maxsize=5000
    self.max=-1
    self.l1=[]
  def  setmaxsize(self,s):
    if isinstance(s,int)==False:
      print('your input is not a number!')
    elif s<self.maxsize:
      print('Do not support shrink!')
    else:
      self.maxsize=s
  def push(self,a):
    if self.max<self.maxsize-1:
      self.l1.append(a)
      self.max += 1
    else:
      print('The stack is full!')  
  def  pop(self):
    if self.max>-1:
      res=self.l1.pop(-1)
      self.max -= 1
      return res
    else:
      print('The stack is empty!')
  def count(self):
    return self.max+1
  def getmaxsize(self):
    return self.maxsize


說明:
類mystack包含一下method:
setmaxsize(s):設定stack的最大容量,要求輸入整數,stack只能擴大,不能縮小
getmaxsize():獲得stack的最大容量
count():獲得stack當前所含元素數量
push(a):將元素推入stack
pop:從stack中獲取一個元素