Frage im Vorstellungsgespräch bei Pocket Gems

Implement a queue using two stacks.

Antworten zu Vorstellungsgespräch

Anonym

16. Feb. 2012

This one was easy.

Anonym

22. Feb. 2012

#include #include using namespace std; //class MyQueue template class MyQueue { public: MyQueue(){} // pay attention to this ~MyQueue() {} void push(T element) ; void pop() ; bool isEmpty() ; T front() ; T back() ; private: stack stack1 ; stack stack2 ; }; // stack1: newest elements // stack2: oldest elements template void MyQueue::push(T element) { stack1.push(element) ; } // pop the oldest element in the queue template void MyQueue::pop() { if ( stack2.empty()) // change to oldest { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } stack2.pop(); } // oldest template T MyQueue::front() { if( stack2.empty() ) { while (!stack1.empty()) { stack2.push(stack1.top()); stack1.pop(); } } return stack2.top() ; } template T MyQueue::back() { if( stack1.empty() ) { while (!stack2.empty()) { stack1.push(stack2.top()); stack2.pop(); } } return stack1.top(); } template bool MyQueue::isEmpty() { if (stack1.empty() && stack2.empty()) { return true ; } else return false ; }