forked from Adityaranjanpatra/Btecky2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CircularQueue.py
74 lines (62 loc) · 1.88 KB
/
CircularQueue.py
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
73
74
class CircularQueue:
def __init__(self, capacity):
self.capacity = capacity
self.queue = [None] * capacity
self.front = self.rear = -1
def is_empty(self):
return self.front == self.rear == -1
def is_full(self):
return (self.rear + 1) % self.capacity == self.front
def enqueue(self, item):
if self.is_full():
print("Queue is full. Cannot enqueue.")
return
elif self.is_empty():
self.front = self.rear = 0
else:
self.rear = (self.rear + 1) % self.capacity
self.queue[self.rear] = item
def dequeue(self):
if self.is_empty():
print("Queue is empty. Cannot dequeue.")
return None
elif self.front == self.rear:
item = self.queue[self.front]
self.front = self.rear = -1
else:
item = self.queue[self.front]
self.front = (self.front + 1) % self.capacity
return item
def peek(self):
if self.is_empty():
print("Queue is empty.")
return None
return self.queue[self.front]
def display(self):
if self.is_empty():
print("Queue is empty.")
elif self.front <= self.rear:
for i in range(self.front, self.rear + 1):
print(self.queue[i], end=" ")
print()
else:
for i in range(self.front, self.capacity):
print(self.queue[i], end=" ")
for i in range(0, self.rear + 1):
print(self.queue[i], end=" ")
print()
# Example usage:
cq = CircularQueue(5)
cq.enqueue(1)
cq.enqueue(2)
cq.enqueue(3)
cq.enqueue(4)
cq.enqueue(5)
print("Queue elements:")
cq.display()
print("Dequeue:", cq.dequeue())
print("Dequeue:", cq.dequeue())
cq.enqueue(6)
cq.enqueue(7)
print("Queue elements after enqueue:")
cq.display()