Implement the following operations of a queue using stacks.
push to top
, peek/pop from top
, size
, and is empty
operations are valid.
class Queue { public: // Push element x to the back of queue. void push(int x) { instk.push(x); } // Removes the element from in front of queue. void pop(void) { if(outstk.empty()){ while(!instk.empty()){ outstk.push(instk.top()); instk.pop(); } } outstk.pop(); } // Get the front element. int peek(void) { if(outstk.empty()){ while(!instk.empty()){ outstk.push(instk.top()); instk.pop(); } } return outstk.top(); } // Return whether the queue is empty. bool empty(void) { return instk.empty() && outstk.empty(); } private: stack<int> instk; stack<int> outstk; };
Implement the following operations of a stack using queues.
push to back
, peek/pop from front
, size
, and is empty
operations are valid.
class Stack { public: // Push element x onto stack. void push(int x) { if(que1.empty()){ que2.push(x); }else{ que1.push(x); } } // Removes the element on top of the stack. void pop() { if(que1.empty()){ while(que2.size() != 1){ que1.push(que2.front()); que2.pop(); } que2.pop(); }else{ while(que1.size() != 1){ que2.push(que1.front()); que1.pop(); } que1.pop(); } } // Get the top element. int top() { int x = 0; if(que1.empty()){ while(!que2.empty()){ x = que2.front(); que2.pop(); que1.push(x); } }else{ while(!que1.empty()){ x = que1.front(); que1.pop(); que2.push(x); } } return x; } // Return whether the stack is empty. bool empty() { return que1.empty() && que2.empty(); } private: queue<int> que1; queue<int> que2; };
232. Implement Queue using Stacks,225. Implement Stack using Queues
原文:http://www.cnblogs.com/zengzy/p/5059345.html