剑指Offer—用两个栈实现队列

题目链接:用两个栈实现队列
用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
注意:不必每次都交换两个栈中的元素

class Solution
{
public:
    void push(int node) {
        if(stack1.empty()){
            if(stack2.empty()){
                stack1.push(node);
            }else{
                while(!stack2.empty()){
                    int tmp = stack2.top();
                    stack2.pop();
                    stack1.push(tmp);
                }
                stack1.push(node);
            }
                
        }else{
            stack1.push(node);
        }
        
    }

    int pop() {
        if(!stack1.empty()){
            if(!stack2.empty()){
                int tmp = stack2.top();
                stack2.pop();
                return tmp;
            }else{
                while(!stack1.empty()){
                    int tmp = stack1.top();
                    stack1.pop();
                    stack2.push(tmp);
                }
                int tmp = stack2.top();
                stack2.pop();
                return tmp;
            }
        }else{
            int tmp = stack2.top();
            stack2.pop();
            return tmp;
        }
            
        
    }

private:
    stack<int> stack1;
    stack<int> stack2;
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容