1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
|
class CircleQueue: queueHead = 0 queueTail = 0 queueCacity = 0 queueLength = 0 queue = []
def __init__(self, capacity): self.queueCacity = capacity self.queue = [0] * capacity
def enqueue(self, obj): if(self.isFull()): raise RuntimeError("Queue is Full")
self.queue[self.queueTail] = obj self.queueTail += 1 self.queueTail = self.queueTail % self.queueCacity self.queueLength += 1
return self.queueLength
def dequeue(self): if(self.isEmpoty()): raise RuntimeError("Queue is Empoty") obj = self.queue[self.queueHead] self.queueHead += 1 self.queueHead = self.queueHead % self.queueCacity self.queueLength -= 1 return obj
def isEmpoty(self): return self.queueLength == 0
def isFull(self): return self.queueLength == self.queueCacity
circleQueue = CircleQueue(5)
assert circleQueue.enqueue(1) == 1 assert circleQueue.enqueue(2) == 2 assert circleQueue.enqueue(3) == 3 assert circleQueue.enqueue(4) == 4 assert circleQueue.enqueue(5) == 5
assert circleQueue.queueLength == 5 assert circleQueue.queueTail == 0 assert circleQueue.queueHead == 0
assert circleQueue.dequeue() == 1 assert circleQueue.dequeue() == 2 assert circleQueue.dequeue() == 3 assert circleQueue.dequeue() == 4 assert circleQueue.dequeue() == 5
assert circleQueue.queueTail == 0 assert circleQueue.queueHead == 0
assert circleQueue.enqueue(6) == 1
assert circleQueue.queueTail == 1 assert circleQueue.queueHead == 0
|
环形队列的关键是能让头索引和尾索引能够在整个环形队列中自己循环