Problem
Implement a queue using stack.
Solution
We can implement a queue using two stacks. while enqueueing we will put into stack one. while dequeuing we will pop from stack two. when stack two is empty we will pop the stack one and put all items into stack two.
Code
import java.util.Stack; public class QueueUsingStack { private Stack<Integer>stackPop=new Stack<Integer>(); private Stack<Integer>stackPush=new Stack<Integer>(); public void enqueue(int a) { stackPush.push(a); } public int dequeue() { if(stackPop.isEmpty()) while(!stackPush.isEmpty()) stackPop.push(stackPush.pop()); return stackPop.pop(); } }
No comments:
Post a Comment