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;
再写一个程序文件,stacktest.py,使用栈,内容如下:
#!/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();