Implementing Queue using Stack is not difficult. Let me make it easy for you. I have provided a diagram for explanation try to understand it what we are doing.
To implement Queue we need two stacks. Why??
Stack supports Last In First Out, and Queue supports First In First Out. If we will use one Stack, the last element will pop out first. And this will return reverse of queue.
With two stacks, first we will add all the elements to one stack, then to print front element of queue, we will start popping elements from stack1 and add to stack2. Now, stack2 will return what we want. The top element of stack2 will be front of queue. And we know how to pop elements from stack, Right.
Let's see code now -
def Push(x,stack1,stack2):
stack2.append(x)
def Pop(stack1,stack2):
if len(stack2)!=0:
top = stack2.pop()
elif len(stack2)==0:
return -1
while len(stack2)!=0:
stack1.append(top)
top = stack2.pop()
while len(stack1)!=0:
temp = stack1.pop()
stack2.append(temp)
return top
Everytime, we will call pop() function, it will return front of queue.
I hope you understood the concept. If you have any doubt do comment, I will help you.
Comments
Post a Comment