|
| 1 | +""" |
| 2 | +Design your implementation of the circular queue. The circular queue is a linear data structure |
| 3 | +in which the operations are performed based on FIFO (First In First Out) principle |
| 4 | +and the last position is connected back to the first position to make a circle. It is also called "Ring Buffer". |
| 5 | +
|
| 6 | +One of the benefits of the circular queue is that we can make use of the spaces in front of the queue. |
| 7 | +In a normal queue, once the queue becomes full, we cannot insert the next element |
| 8 | +even if there is a space in front of the queue. But using the circular queue, we can use the space to store new values. |
| 9 | +
|
| 10 | +link - https://leetcode.com/problems/design-circular-queue/ |
| 11 | +
|
| 12 | +runtime - 72ms |
| 13 | +memory - 14.6 mb |
| 14 | +
|
| 15 | +time complexity - O(n) |
| 16 | +space complexity - O(n) |
| 17 | +
|
| 18 | +""" |
| 19 | + |
| 20 | + |
| 21 | + |
| 22 | +class MyCircularQueue: |
| 23 | + |
| 24 | + def __init__(self, k: int): |
| 25 | + """ |
| 26 | + Initialize your data structure here. Set the size of the queue to be k. |
| 27 | + """ |
| 28 | + self.queue = [None] *k |
| 29 | + self.head = 0 |
| 30 | + self.tail = -1 |
| 31 | + self.size = 0 |
| 32 | + self.max_size = k |
| 33 | + |
| 34 | + |
| 35 | + def enQueue(self, value: int) -> bool: |
| 36 | + """ |
| 37 | + Insert an element into the circular queue. Return true if the operation is successful. |
| 38 | + """ |
| 39 | + if self.isFull(): |
| 40 | + return False |
| 41 | + self.tail = (self.tail +1) % self.max_size |
| 42 | + self.queue[self.tail] = value |
| 43 | + self.size += 1 |
| 44 | + return True |
| 45 | + |
| 46 | + def deQueue(self) -> bool: |
| 47 | + """ |
| 48 | + Delete an element from the circular queue. Return true if the operation is successful. |
| 49 | + """ |
| 50 | + if self.isEmpty(): |
| 51 | + return False |
| 52 | + self.queue[self.head] = None |
| 53 | + self.head = (self.head +1) % self.max_size |
| 54 | + self.size -= 1 |
| 55 | + return True |
| 56 | + |
| 57 | + def Front(self) -> int: |
| 58 | + """ |
| 59 | + Get the front item from the queue. |
| 60 | + """ |
| 61 | + return -1 if self.isEmpty() else self.queue[self.head] |
| 62 | + |
| 63 | + def Rear(self) -> int: |
| 64 | + """ |
| 65 | + Get the last item from the queue. |
| 66 | + """ |
| 67 | + return -1 if self.isEmpty() else self.queue[self.tail] |
| 68 | + |
| 69 | + def isEmpty(self) -> bool: |
| 70 | + """ |
| 71 | + Checks whether the circular queue is empty or not. |
| 72 | + """ |
| 73 | + return self.size == 0 |
| 74 | + |
| 75 | + |
| 76 | + def isFull(self) -> bool: |
| 77 | + """ |
| 78 | + Checks whether the circular queue is full or not. |
| 79 | + """ |
| 80 | + return self.size == self.max_size |
0 commit comments