Created
April 28, 2024 12:26
-
-
Save AriTedeschi/25d137a27f02b86116ae422714dde55c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class circularQueue: | |
def __init__(self,size): | |
# since python doesn`t have arrays i`m using list in place (by default a "list" is a linked list in python) | |
self.arr = [] | |
self.head=0 | |
self.tail=0 | |
self.size=size | |
for i in range(0,size): | |
self.arr.append(None) | |
def next(self,ptr): | |
return (ptr+1) % (self.size) | |
def isEmpty(self): | |
return self.head == self.tail | |
def isFull(self): | |
return self.head == self.next(self.tail) | |
def push(self,e): | |
if self.arr[self.tail] is None: | |
self.arr[self.tail]=e | |
if not self.isFull(): | |
self.tail = self.next(self.tail) | |
print(f'push={e}\n {self.arr}\n head={self.head}\n tail={self.tail}\n') | |
def pop(self): | |
if not self.isEmpty(): | |
self.arr[self.head]=None | |
if self.isFull(): | |
self.tail = self.next(self.tail) | |
self.head=self.next(self.head) | |
print(f'pop\n {self.arr}\n head={self.head}\n tail={self.tail}\n') | |
queue = circularQueue(4) | |
queue.push(1) | |
queue.push(2) | |
queue.push(3) | |
queue.push(4) | |
queue.push(5) | |
queue.pop() | |
queue.push(5) | |
queue.push(6) | |
queue.pop() | |
queue.push(6) | |
queue.push(6) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment