# python实现堆栈与队列的方法

1、python实现堆栈，可先将stack类写入文件stack.py，在其它程序文件中使用from stack import stack，然后就可以使用堆栈了。

stack.py的程序:

class stack():
def __init__(self,size):
self.size=size;
self.stack=[];
self.top=-1;
def push(self,ele): #入栈之前检查栈是否已满
if self.isfull():
raise exception(“out of range”);
else:
self.stack.append(ele);
self.top=self.top+1;
def pop(self): # 出栈之前检查栈是否为空
if self.isempty():
raise exception(“stack is empty”);
else:
self.top=self.top-1;
return self.stack.pop();

def isfull(self):
return self.top+1==self.size;
def isempty(self):
return self.top==-1;

#!/usr/bin/python
from stack import stack
s=stack(20);
for i in range(3):
s.push(i);
s.pop()
print s.isempty();

2、python 实现队列:

class queue():
def __init__(self,size):
self.size=size;
self.front=-1;
self.rear=-1;
self.queue=[];
def enqueue(self,ele): #入队操作
if self.isfull():
raise exception(“queue is full”);
else:
self.queue.append(ele);
self.rear=self.rear+1;
def dequeue(self): #出队操作
if self.isempty():
raise exception(“queue is empty”);
else:
self.front=self.front+1;
return self.queue[self.front];
def isfull(self):
return self.rear-self.front+1==self.size;
def isempty(self):
return self.front==self.rear;

q=queue(10);
for i in range(3):
q.enqueue(i);
print q.dequeue();
print q.isempty();

Posted in 未分类