循环队列
class CircularQueue():
def __init__(self, size=1):
self.size = size
self.data = [None for i in range(size)]
self.front = self.rear = -1
def put(self, data):
if ((self.rear + self.front + 1) >= self.size
or self.front > self.rear):
# condition if queue is full
# print('333')
self.data[self.rear] = data
self.front = (self.front + 1) % self.size
self.rear = (self.rear + 1) % self.size
elif (self.front == self.rear):
# condition for empty queue
# print('111')
self.front = 0
self.data[self.front] = data
self.rear = (self.front + 1) % self.size
else:
# next position of rear
# print('222')
self.data[self.rear] = data
self.rear = (self.rear + 1) % self.size
def empty(self):
if (self.front == -1):
return True
return False
def get(self):
if self.empty():
return None
rtn = self.data[self.front]
self.data[self.front] = None
if (self.front != self.rear):
self.front = (self.front + 1) % self.size
else:
self.front = self.rear = -1
return rtn
def display(self):
print(self.data, self.front, self.rear)
if __name__ == '__main__':
ob = CircularQueue(5)
for i in range(12):
ob.put(i)
ob.display()
print('---------------------')
for i in range(12):
print(ob.get())
ob.display()