Implement the following operations of a queue using stacks.
push(x) – Push element x to the back of queue. pop() – Removes the element from in front of queue. peek() – Get the front element. empty() – Return whether the queue is empty.
classQueue { public: // Push element x to the back of queue. voidpush(int x){ s1.push(x); }
// Removes the element from in front of queue. voidpop(void){ this->peek(); return s2.pop(); }
// Get the front element. intpeek(void){ if(!s2.empty()) return s2.top(); while(!s1.empty()){ int temp = s1.top(); s2.push(temp); s1.pop(); } return s2.top(); }
// Return whether the queue is empty. boolempty(void){ return s1.empty() && s2.empty(); } private: stack<int> s1, s2; };