정해진 길이 n (예에서는 6)의 리스트를 확보해 두고 시작
예시
Q.enqueue(A) # rear: A
Q.enqueue(B) # rear: B
Q.enqueue(C) # rear: C
Q.enqueue(D) # rear: D
r1 = Q.dequeue() # front: A, r1: A
r2 = Q.dequeue() # front: B, r2: B
Q.enqueue(E) # rear: E
Q.enqueue(F) # rear: F
Q.enqueue(G) # rear: G
r3 = Q.dequeue() # front: C, r3: C
front와 rear를 적절히 계산하여 배열을 환형으로 재활용
배열로 구현한 환형 큐
def __init(self, n):
self.maxCount = n
self.data = [None]*n
self.count = 0
self.front = -1
self.rear = -1
def size(self):
return self.count
def isEmpty(self):
return self.count == 0
def isFull(self):
return self.count == self.maxCount
def enqueue(self, x):
if self.ifFull():
raise IndexError('Queue full')
self.rear = (self.rear + 1) % self.maxCount
self.data[self.rear] = x
self.count += 1
def dequeue(self):
if self.count == 0:
raise IndexError('Queue empty')
self.front = (self.front + 1) % self.maxCount
x = self.data[self.front]
self.count -= 1
return x
def peek(self):
if self.isEmpty():
raise IndexError('Queue empty')
return self.data[(self.front + 1) % self.maxCount]