Week6 Stack Uisng Queue
Week6 Stack Uisng Queue
Queues
Queue using Stack
deQueue(q):
If stack1 is empty then error
Pop an item from stack1 and return it
Here time complexity will be O(1)
Queue Using Stack: Enqueue rear
operation
Create two stacks
1 2 3
0 1 2
Insert/Push 1,2,3 in to the stack front
Push(1)
in to primary
stack
operation
1 2 3
0 1 2
front
Pop all the elements from
primary stack and push in
secondary stack then
push second element in to
the stack.
operation
Which element is dequeue from queue ? 1 2 3
Which element is pop from primary stack?
0 1 2
front
Pop all the elements from
primary stack and push in
secondary stack then
push second element in to
the stack.
1
Pop() Primary Stack
2
Push(1) Secondary Stack
3
Push(3)
in to primary stack
Primary Stack Secondary/temp
Stack Pop() secondary Stack
Push(2) primary Stack
Push(1) primary Stack
Queue Using Stack: Enqueue
operation costly
Queue Using Stack: Dequeue
operation costly
1. Using two stacks primary_stack &
secondary_stack.
2. Push the element in primary_stack.
3. If the primary_stack is not empty, move all the
elements present in the primary_stack(S1) to
the secondary_stack(S2), one by one. Then
remove the element at the top from the
secondary stack, and then move back all the
elements from the secondary_stack to the
primary_stack.
4. The purpose of moving all the elements present
in the primary stack to the secondary stack is to
reverse the order of the elements, because of
which the first element inserted into the
primary_stack(queue), is positioned at the top
Queue Using Stack: Dequeue
operation costly
enQueue(q, x)
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything
from stack1 to stack2.
3) Pop the element from stack2 and return it.
Here time complexity will be O(n)
Queue Using Stack: Enqueue rear
operation
Create two stacks
Insert/Push 1,2,3 in to the stack 1 2 3
0 1 2
front
3 1
2 2
1 3