zoukankan      html  css  js  c++  java
  • 用两个栈实现队列

    用两个栈实现队列

    题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

    stack1用来push, stack2用来pop

    版本一: 每次pop操作都需要从stack1复制到stack2中, 并清空stack1, 其实在stack2不为空时, 执行pop操作不需要复制与清空操作

    class Solution
    {
    public:
        void push(int node) {
            stack1.push(node);
        }
    
        int pop() {
            int ret;
            
            while(!stack2.empty()) {
                stack2.pop();
            }
            
            while(!stack1.empty()) {
                stack2.push(stack1.top());
                stack1.pop();
            }
            
            ret = stack2.top();
            stack2.pop();
            
            while(!stack2.empty()) {
                stack1.push(stack2.top());
                stack2.pop();
            }
            
            return ret;
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    

    版本二: 当stack2不为空时, pop操作不清空stack1, 否则执行复制操作, 并清空stack1

    class Solution
    {
    public:
        void push(int node) {
            stack1.push(node);
        }
    
        int pop() {
            int ret;
            
            if (stack2.empty()) {
                    while(!stack1.empty()) {
                    stack2.push(stack1.top());
                    stack1.pop();
                }
            }
            
            ret = stack2.top();
            stack2.pop();
            
            return ret;
        }
    
    private:
        stack<int> stack1;
        stack<int> stack2;
    };
    
  • 相关阅读:
    spring-schedule
    数字电路
    面试题
    CMOS集成门电路
    TTL特殊门电路
    TTL反相器的外部特性
    TTL集成门电路工作原理和电压传输特性
    半导体器件的开关特性和分立元件门电路
    逻辑函数的公式化减法
    php 获取当前文件名称
  • 原文地址:https://www.cnblogs.com/hesper/p/10416099.html
Copyright © 2011-2022 走看看