ITPub博客

首页 > IT职业 > IT生活 > Python实现栈

Python实现栈

IT生活 作者:cookye 时间:2021-09-09 09:20:29 0 删除 编辑

# -*- 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

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1369/viewspace-2802429/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-04-15

  • 博文量
    91
  • 访问量
    502