python实现一个循环队列

python实现一个循环队列


```python
class RecyQueue:
    '''
    顺序结构循环队列
    头指针指向队头元素,尾指针指向队尾元素的下一个位置
    牺牲一个空间位置用于区分队空队满-------这是链表才有的特性,数组没有,因为默认有一个头节点和尾节点
        ----------------这里用%的特性实现了循环-------
    队空:front == rear
    队满:(rear + 1) % capacity == front
    '''
    def __init__(self, capacity=20):
        self.capacity = capacity
        self.data = [None] * self.capacity
        self.front = self.rear = 0
        
    def isEmpty(self):
        return self.front == self.rear
    
    def isFull(self):
        return (self.rear + 1) % self.capacity == self.front
    
    def enqueue(self, value):
        if self.isFull():
            raise Exception('Enqueue failed: Queue is full')
        else:
            self.data[self.rear] = value
            self.rear = (self.rear + 1) % self.capacity
            
    def dequeue(self):
        if self.isEmpty():
            raise Exception('Dequeue failed: Queue is empty')
        else:
            x = self.data[self.front]
            self.front = (self.front + 1) % self.capacity
            return x

————————————————

原文链接:https://blog.csdn.net/shichensuyu/article/details/90181375


你可能感兴趣的:(数据结构)