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
| class CQueue: MAXSIZE = 10 def __init__(self): self.__container = [None for _ in range(CQueue.MAXSIZE+1)] self.__head = 0 self.__tail = 0
def is_empty(self): if self.__head == self.__tail: return True return False
def is_full(self): next = self.__step_forward(self.__tail) if next == self.__head: return True return False
def enqueue(self, data): if self.is_full(): raise Exception("The queue is full") self.__tail = self.__step_forward(self.__tail) self.__container[self.__tail] = data
def dequeue(self): if self.is_empty(): raise Exception("The queue is empty") self.__head = self.__container[self.__head + 1] self.__head = self.__step_forward(self.__head) return self__head
def peek(self): if self.is_empty(): raise Exception("The queue is empty") return self.__container[self.__head + 1]
def __step_forward(self, x): x += 1 if x >= CQueue.MAXSIZE+1: x = 0 return x
def __str__(self): return str(self.__container)
if __name__ =="__main__": cq = CQueue()
for i in range(9+1): cq.enqueue(i + 1) print(f"enqueue: {i+1}")
for i in range(5+1): print("dequeue: ", cq.dequeue())
print("tail: ", cq._CQueue__tail) print("head: ", cq._CQueue__head) print("peek: ", cq.peek()) print("container: ", cq) print("is full? ", cq.is_full()) print("is empty? ", cq.is_empty())
|