Frage im Vorstellungsgespräch bei Groupon

Now implement a queue using a stack.

Antwort im Vorstellungsgespräch

Anonym

16. Sep. 2016

//two stacks class MyQueue { Stack temp = new Stack(); Stack value = new Stack(); // Add element x to the back of queue. public void add(int x) { if(value.isEmpty()){ value.push(x); }else{ while(!value.isEmpty()){ temp.push(value.pop()); } value.push(x); while(!temp.isEmpty()){ value.push(temp.pop()); } } } // Removes the element from in front of queue. public void remove() { value.pop(); } // Get the front element. public int element() { return value.peek(); } // Return whether the queue is empty. public boolean isEmpty() { return value.isEmpty(); } }