Python 栈和队列
1、Python栈的实现
#encoding=UTF-8
'''
Created on 2016年9月25日
@author: sx
'''
class Stack():
def __init__(self,lenth):
self.stack=[]
self.max=lenth
self.top=len(self.stack)-1
def isempty(self):
if self.top==-1:
print("空")
return True
else:
print("not null")
return None
def isfull(self):
if self.top==self.max-1:
print("满")
return True
else:
print("not full")
return None
def pull(self,data):
if self.isfull():
print("无法插入,满了")
return False
else:
self.stack.append(data)
self.top=self.top+1
def push(self):
if self.isempty():
print("无法取出,空了")
return False
else:
print(self.stack[self.top])
self.stack=self.stack[:-1]
self.top=self.top-1
def printf(self):
print(self.stack)
sx=Stack(10)
for i in range(1,12):
sx.pull(i)
sx.printf()
for i in range(1,12):
sx.push()
sx.printf()
2、Python队列的实现
#encoding=UTF-8
'''
Created on 2016年9月25日
@author: sx
'''
class Queue():
def __init__(self,lenth):
self.stack=[]
self.max=lenth
self.top=len(self.stack)-1
def isempty(self):
if self.top==-1:
print("空")
return True
else:
print("not null")
return None
def isfull(self):
if self.top==self.max-1:
print("满")
return True
else:
print("not full")
return None
def pull(self,data):
if self.isfull():
print("无法插入,满了")
return False
else:
self.stack.append(data)
self.top=self.top+1
def push(self):
if self.isempty():
print("无法取出,空了")
return False
else:
print(self.stack[0])
del self.stack[0]
self.top=self.top-1
def printf(self):
print(self.stack)
def clear(self):
self.stack=[]
self.top=-1
sx=Queue(10)
sx.isempty()
sx.isfull()
sx.pull(2)
sx.printf()
sx.pull(3)
sx.pull(4)
sx.pull(5)
sx.printf()
sx.pull(6)
sx.printf()
sx.push()
sx.printf()
sx.push()
sx.printf()
sx.clear()
sx.printf()
for i in range(1,12):
sx.pull(i)
sx.printf()
for i in range(1,12):
sx.push()
sx.printf()