You are viewing a single comment's thread. Return to all comments →
Java
public static class QueueUsingTwoStacks<T> { private Stack<T> stack1 = new Stack<>(); private Stack<T> stack2 = new Stack<>(); public void enqueue(T a) { stack1.push(a); } public T dequeue() { fillStack2IfEmpty(); return stack2.pop(); } public T peek() { fillStack2IfEmpty(); return stack2.peek(); } private void fillStack2IfEmpty() { if (stack2.isEmpty()) { while (!stack1.isEmpty()) { stack2.push(stack1.pop()); } } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
Java