美文网首页
python实现栈和队列

python实现栈和队列

作者: D_w | 来源:发表于2021-08-16 21:31 被阅读0次

    栈,特点先入后出,FILO,python中列表即为栈的实现,append方法相当于入栈,pop方法相当于出栈

    python中有的队列工具,collections.deque,queue.Queue

    python实现队列

    class MyQueue

    class MyQuene:
        def __init__(self, capacity):
            self.list = [None]* capacity
            self.front = 0
            self.rear = 0
    
        def enqueue(self, element):
            if (self.rear+1) % len(self.list) == self.front:
                raise Exception("queue is full")
            self.list[self.rear] = element
            self.rear = (self.rear+1) % len(self.list)
            
        def dequeue(self):
            if self.rear == self.front:
                raise Exception("queue is empty")
            dequeue_element = self.list[self.front]
            self.front = (self.front+1)%len(self.list)
            return dequeue_element
        
        def output(self):
            i = self.front
            while i != self.rear:
                print(self.list[i])
                i = (i+1)%len(self.list)
    

    相关文章

      网友评论

          本文标题:python实现栈和队列

          本文链接:https://www.haomeiwen.com/subject/axevbltx.html