首页 > 编程语言 >Python实现队列,堆栈

Python实现队列,堆栈

时间:2022-09-29 16:33:36浏览次数:53  
标签:return Python self 队列 isempty 堆栈 top def size

一、队列


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)
for i in range(3):
    print(q.dequeue())
print(q.isempty())

二、堆栈

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


s = Stack(20)
for i in range(3):
    s.push(i)
    
for i in range(3):
    print(s.pop())
print(s.isempty())

标签:return,Python,self,队列,isempty,堆栈,top,def,size
From: https://www.cnblogs.com/hikk/p/16742030.html

相关文章