Implement Queue using Stack (with Example)

preview_player
Показать описание
This lecture explains two methods to implement queue using stacks only. The first method assumes Enqueue operation to be costly and second method assumes dequeue operation to be costly. If you find any difficulty or have any query then do COMMENT below. PLEASE help our channel by SUBSCRIBING and LIKE our video if you found it helpful...CYA :)

Algo: EnQueue Costly

enQueue(q, x)
1) While stack1 is not empty, push everything from stack1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
Here time complexity will be O(n)

deQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
Here time complexity will be O(1)

Algo: DeQueue Costly

enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
Here time complexity will be O(1)

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)

Рекомендации по теме
Комментарии
Автор

Great video sir. Hope your channel gets the success it deserves.

Dankman
Автор

one more method .
Push all the elements in one stack
When to pop:
1. check if stack2 is empty
transfer from stack one to stack 2 then pop
2. check after check 1 stack 2 is empty then empty queue
3. finally pop from stack 2
Why again and again push, pop . Do it only one time.

vinoddiwan
Автор

so smooth explanation and audio quality is superb... can you please how did you get such audio quality

aniruddhachunne
Автор

thank you teacher, this is very clear explanation, thank you.

linlinli
Автор

Excellent explanation Sir.
Thanks 😊👍

SaumyaSharma
Автор

sir superb content sir pls keep the code in cpp it makes things much better

mahadevsai
Автор

Why we are using stack to implement a queue ? Using array the both enqueue and dequeue operation takes O(1), Is there any special application ... little confused, could you please help me to understand ?

duraivelperumal
Автор

Bro can you explain the recursive call stack method to solve this problem?

bikramjitdas
Автор

Its wrong you are not following the stack operation rule properly. Kindly do that.

shrutisaxena