面试题 03.04. 化栈为队

编程入门 行业动态 更新时间:2024-10-22 15:43:59

<a href=https://www.elefans.com/category/jswz/34/1769418.html style=面试题 03.04. 化栈为队"/>

面试题 03.04. 化栈为队

​​题目来源:

        leetcode题目,网址:面试题 03.04. 化栈为队 - 力扣(LeetCode)

解题思路:

       初始时,有两个空栈 stack1 和  stack2,将 stack1 作为输入栈,stack2 作为输出栈。 

        入栈,直接入栈 stack1.

        出栈,若 stack2 非空,直接从 stack 2 中出栈;否则,将 stack1 中元素出栈并压入 stack2 中,然后再将 stack2 栈顶元素出栈。

        查看栈顶元素,若 stack2 非空,直接返回 stack 2 栈顶元素即可;否则,将 stack1 中元素出栈并压入 stack2 中,然后返回 stack2 栈顶元素。

        判空,两站大小之和是否为 0.

解题代码:

class MyQueue {
private:stack<int> stack1;stack<int> stack2;
public:/** Initialize your data structure here. */MyQueue() {while(!stack1.empty()){stack1.pop();}while(!stack2.empty()){stack2.pop();}}/** Push element x to the back of queue. */void push(int x) {stack1.push(x);}/** Removes the element from in front of queue and returns that element. */int pop() {if(stack2.empty()){while(!stack1.empty()){stack2.push(stack1.top());stack1.pop();}}int temp=stack2.top();stack2.pop();return temp;}/** Get the front element. */int peek() {if(stack2.empty()){while(!stack1.empty()){stack2.push(stack1.top());stack1.pop();}}return stack2.top();}/** Returns whether the queue is empty. */bool empty() {return stack1.size()+stack2.size()==0;}
};/*** 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();*/
 

总结:

        和官方题解思路一样。


更多推荐

面试题 03.04. 化栈为队

本文发布于:2023-12-03 11:18:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1654770.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:面试题

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!