In this source code example, we will write a code to implement the Deque data structure in Python.
A double-ended queue, or deque, has the feature of adding and removing elements from either end.Deque Implementation in Python
class Deque(object):
def __init__(self, limit = 10):
self.queue = []
self.limit = limit
def __str__(self):
return ' '.join([str(i) for i in self.queue])
# check if queue is empty
def isEmpty(self):
return len(self.queue) <= 0
# check if queue is full
def isFull(self):
return len(self.queue) >= self.limit
# for inserting at rear
def insertRear(self, data):
if self.isFull():
return
else:
self.queue.insert(0, data)
# for inserting at front end
def insertFront(self, data):
if self.isFull():
return
else:
self.queue.append(data)
# deleting from rear end
def deleteRear(self):
if self.isEmpty():
return
else:
return self.queue.pop(0)
# deleting from front end
def deleteFront(self):
if self.isFull():
return
else:
return self.queue.pop()
if __name__ == '__main__':
myDeque = Deque()
myDeque.insertFront(1) # 1
myDeque.insertRear(2) # 2 1
myDeque.insertFront(3) # 2 1 3
myDeque.insertRear(10) #10 2 1 3
print(myDeque)
myDeque.deleteRear() # 2 1 3
print(myDeque)
myDeque.deleteFront() # 2 1
print(myDeque)
Output:
10 2 1 3
2 1 3
2 1
Related Data Structures in Python
- Stack Implementation in Python
- Queue Implementation in Python
- Deque Implementation in Python
- Singly Linked List Implementation in Python
- Doubly Linked List Implementation in Python
- Circular Linked List Implementation in Python
- PriorityQueue Implementation in Python
- Circular Queue Implementation in Python
- Binary Search Tree Implementation in Python
- Stack Implementation Using Linked List in Python
- Stack Implementation Using Doubly Linked List in Python
Free Spring Boot Tutorial - 5 Hours Full Course
Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course