232. 用栈实现队列

原题链接:232. 用栈实现队列

 solution:

class MyQueue {
private:stack stin;    //入队栈stack stout;   //出队栈public:MyQueue() {}void push(int x) {stin.push(x);}int pop() {int res = 0;if(!stout.empty()){ //如果出队栈不为空,则直接popres = stout.top();stout.pop();return res;}else if(!stin.empty()){ //当出堆栈为空,入队栈不为空更新出队栈while(!stin.empty()){stout.push(stin.top()); //入队栈顶元素压入出队栈stin.pop();}}res = stout.top();stout.pop();return res;}int peek() {int res = 0;if(!stout.empty()){res = stout.top();return res;}           else if(!stin.empty()){ //当出堆栈为空,入队栈不为空更新出队栈while(!stin.empty()){stout.push(stin.top()); //入队栈顶元素压入出队栈stin.pop();}}res = stout.top();return res;}bool empty() {if(stin.empty() && stout.empty())return true;return false;}
};/*** Your MyQueue object will be instantiated and called as such:* MyQueue* obj = new MyQueue();* obj->push(x);* int param_2 = obj->pop();* int param_3 = obj->peek();* bool param_4 = obj->empty();*/

 


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部