For implementing stack, we require two stacks, although it can be implemented using a single queue, but here we are going to see how to do it using two queues.
Queue is the reverse of Stack.
Why? - Queue works on FIFO(First In First Out), and Stack works on LIFO (Last In First Out).
How we are going to do it?
1. Initialize two queues queue_1, and queue_2.
2. Define two functions - push(item) and pop().
3. In push, what we are doing? -
- Append item in queue_2, then pop all elements from queue_1, and append to queue_2.
- Now, pop all elements from queue_2, and append to queue_1
Code -
queue_1 = []
queue_2 = []
def push(x):
global queue_1
global queue_2
queue_2.append(x)
while len(queue_1)!=0:
top = queue_1.pop()
queue_2.append(top)
while len(queue_2)!=0:
temp = queue_2.pop()
queue_1.append(temp)
def pop():
global queue_1
global queue_2
temp = -1
if len(queue_1)!=0:
temp = queue_1.pop()
return temp
I hope you understood the implementation, if you have any doubt do comment, I will help you out.
Comments
Post a Comment