Python實現棧

 

# -*- coding:utf-8 -*-
class Stack():
 #初始化棧,並給定棧的大小
 def __init__(self,size):
  self.stack=[]
  self.size=size
  self.top=-1
 #判斷棧是否滿了,棧滿返回True
 def Full(self):
  if self.top==(self.size-1):
   return True
  else:
   return False
 #判斷棧是否爲空,爲空返回True
 def Empty(self):
  if self.top==-1:
   return True
  else:
   return False
 #入棧
 def stackin(self,content):
  if self.Full():
   print 'The stack is full!'
  else:
   self.stack.append(content)
   self.top+=1
 #出棧
 def stackout(self):
  if self.Empty():
   print 'The stack is empty!'
   return None
  else:
   content=self.stack[self.top]
   self.stack.pop(self.top)
   self.top-=1
   return content
 #遍歷棧
 def stackall(self):
  if self.Empty():
   print 'The stack is Empty!'
  else:
   while self.top>=0:
    print self.stack[self.top]
    self.top-=1

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章