一.
class Stack(object):
"""docstring for Stack"""
def __init__(self, size):
self.stack = []
self.size = size
self.top = -1
def push(self,content):
if self.full():
print("stack is full")
else:
self.stack.append(content)
self.top = self.top + 1
def pop(self,content):
if self.empty():
print("stack is empty")
else:
self.top = self.top - 1
def empty(self):
if self.top == -1:
return True
else:
return False
def full(self):
if self.top == self.size:
return True
else:
return False
stack = Stack(9)
# stack.push(3)
stack.pop(3)
print(stack.empty())
1.首先定义一个Stack类
初始化这个类,定义self.stack为列表,然后我们在给他添加条件,因为列表是任何位置都可以取元素,而栈是FILO结构.
2.判断栈是否空或者满
空的话就是self.top == -1,满的话就是top指针和栈大小相同,即self.top == self.size
def empty(self):
def full(self):
3.进栈操作如下
def push(self,content):
if self.full():
print("stack is full")
else:
self.stack.append(content)
self.top = self.top + 1
先判断是否满,如果满就放不下了,不满的话,列表追加一个元素,就是我们传进去的content,然后top指针再加1,再赋给self.top,相当于self.top++
注意Python中没有self.top++这种操作,但可以self.top+=1或者相应的self.top-=1
4.出栈操作如下
def pop(self,content):
if self.empty():
print("stack is empty")
else:
self.top = self.top - 1
self.top减去1,然后再赋给self.top
二.
class Stack():
def __init__(self):
self._elems = []
def is_empty(self):
return self._elems == []
def top(self):
if self._elems == []:
print("Stack is empty")
return -1
def push(self,elem):
self._elems.append(elem)
def pop_(self):
if self._elems == []:
print("Stack is empty")
#删除并返回最后一个元素,即删除的元素
return self._elems.pop()
stack = Stack()
stack.push(3)
stack.push(5)
while not stack.is_empty():
print(stack.pop_())