You are viewing a single comment's thread. Return to all comments →
Like many people have pointed out, you don't have to go from old to new. you only need to go from new to old. This problem took longer than expected.
public static class MyQueue<T> { Stack<T> stackNewestOnTop = new Stack<T>(); Stack<T> stackOldestOnTop = new Stack<T>(); public void enqueue(T value) { // Push onto newest stack stackNewestOnTop.push(value); } public T peek() { if(stackOldestOnTop.isEmpty()) { while(!stackNewestOnTop.isEmpty()) { stackOldestOnTop.push(stackNewestOnTop.pop()); } } return stackOldestOnTop.peek(); } public T dequeue() { if(stackOldestOnTop.isEmpty()) { while (!stackNewestOnTop.isEmpty()) { stackOldestOnTop.push(stackNewestOnTop.pop()); } } return stackOldestOnTop.pop(); } }
Seems like cookies are disabled on this browser, please enable them to open this website
Queues: A Tale of Two Stacks
You are viewing a single comment's thread. Return to all comments →
Like many people have pointed out, you don't have to go from old to new. you only need to go from new to old. This problem took longer than expected.