Implement a queue using two stacks. Python code example
Example 1: queues in python
class Queue:
def __init__(self, capacity):
self.front = self.size = 0
self.rear = capacity - 1
self.Q = [None] * capacity
self.capacity = capacity
def isFull(self):
return self.size == self.capacity
def isEmpty(self):
return self.size == 0
def EnQueue(self, item):
if self.isFull():
print("Full")
return
self.rear = (self.rear + 1) % (self.capacity)
self.Q[self.rear] = item
self.size = self.size + 1
print("%s enqueue to queue" %str(item))
def DeQueue(self):
if self.isEmpty():
return "Empty"
print("%s dequeued from queue" %str(self.Q[self.front]))
self.front = (self.front + 1) % (self.capacity)
self.size = self.size - 1
def que_front(self):
if self.isEmpty():
print("The Queue is empty")
print("Front item is ", self.Q[self.front])
def que_rear(self):
if self.isEmpty():
print("Queue is Empty")
print("The rear item is ", self.Q[self.rear])
queue = Queue(30)
queue.EnQueue(10)
queue.EnQueue(20)
queue.EnQueue(30)
queue.EnQueue(40)
queue.EnQueue(50)
queue.que_front()
print()
queue.DeQueue()
queue.que_front()
queue.que_rear()
print()
queue.DeQueue()
queue.que_front()
queue.que_rear()
Example 2: python list as stack and queue
def isEmpty(stk): # checks whether the stack is empty or not
if stk==[]:
return True
else:
return False
def Push(stk,item): # Allow additions to the stack
stk.append(item)
top=len(stk)-1
def Pop(stk):
if isEmpty(stk): # verifies whether the stack is empty or not
print("Underflow")
else: # Allow deletions from the stack
item=stk.pop()
if len(stk)==0:
top=None
else:
top=len(stk)
print("Popped item is "+str(item))
def Display(stk):
if isEmpty(stk):
print("Stack is empty")
else:
top=len(stk)-1
print("Elements in the stack are: ")
for i in range(top,-1,-1):
print (str(stk[i]))
# executable code
if __name__ == "__main__":
stk=[]
top=None
Push(stk,1)
Push(stk,2)
Push(stk,3)
Push(stk,4)
Pop(stk)
Display(stk)