python实现堆栈与队列的方法

WBOY
Release: 2016-06-06 11:21:36
Original
1135 people have browsed it

本文实例讲述了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;


 
再写一个程序文件,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();

希望本文所述对大家的Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!