python实现循环队列

p y t h o n 实 现 循 环 队 列 python实现循环队列 python

Front==tail队列为空
(tail+1)%c == front 队列列满,进行扩容
浪费一个空间来区分满队列和空队列

练习三部曲之一

class LoopQueue(object):
    # 1.成员构造
    def __init__(self, capacity=2):
        self.arr = [None] * (capacity + 1)
        self.front = 0
        self.tail = 0
        self.size = 0

    # 2.魔法方法
    def __str__(self):
        return str(self.arr)

    def __len__(self):
        return len(self.arr)

    def __iter__(self):
        return iter(self.arr)
    
    # 3.返回大小
    def get_size(self):
        return self.size

    def get_capaticty(self):
        return self.__len__() - 1
    
    # 4.判满
    def is_full(self):
        return (self.tail + 1) % len(self.arr) == self.front

    # 5.判空
    def is_empty(self):
        return self.size == 0
    # 6.查
    def get_front(self):
        return self.arr[self.front]
    # 7.增
    def enqueue(self, e):
        if self.is_full():
            self.resize(self.get_capaticty() * 2)
        self.arr[self.tail] = e
        self.tail = (self.tail + 1) % len(self.arr)
        self.size += 1
    # 8.删
    def dequeue(self):
        if self.is_empty():
            raise Exception("Cannot dequeue from en empty queue")

        result = self.arr[self.front]
        self.arr[self.front] = None
        self.front = (self.front + 1) % len(self.arr)
        self.size -= 1

        if self.size < self.get_capaticty() // 4 and self.get_capaticty() > 1:
            self.resize(self.get_capaticty() // 2)
        return result
    
    # 9.附加函数
    def resize(self, new_capacity):
        new_arr = [None] * (new_capacity + 1)
        for i in range(self.size):
            new_arr[i] = self.arr[(i + self.front) % len(self.arr)]

        self.arr = new_arr
        self.front = 0
        self.tail = self.size

练习三部曲之二

class Queue():
    # 1.成员构造
    # 2.返回大小
    # 3.判空
    # 4.增
    # 5.删
class LoopQueue(object):
    # 1.成员构造
    def __init__(self, capacity=2):

    # 2.魔法方法
    def __str__(self):

    def __len__(self):

    def __iter__(self):


    # 3.返回大小
    def get_size(self):


    def get_capaticty(self):


    # 4.判满
    def is_full(self):

    # 5.判空
    def is_empty(self):

    # 6.查
    def get_front(self):

    # 7.增
    def enqueue(self, e):

    # 8.删
    def dequeue(self):

    # 9.附加函数
    def resize(self, new_capacity):
    

练习三部曲之三

class LoopQueue(object):
    # 1.成员构造

    # 2.魔法方法

    # 3.返回大小

    # 4.判满

    # 5.判空

    # 6.查

    # 7.增

    # 8.删

    # 9.附加函数

你可能感兴趣的:(python实现循环队列)