zoukankan      html  css  js  c++  java
  • 剑指05两个栈实现一个队列

    题目描述

    用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
    class Solution
    {
    public:
        void push(int node) {
            stack1.push(node);
            
            
        }

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

    private:
        stack<int> stack1;
        stack<int> stack2;
    };
     
     
    import java.util.Stack;

    public class Solution {
        Stack<Integer> stack1 = new Stack<Integer>();
        Stack<Integer> stack2 = new Stack<Integer>();
        
        public void push(int node) {
            stack1.push(node);
        }
        
        public int pop() {
            if (stack1.empty()&& stack2.empty()){
                throw new RuntimeException("Queue is empty!");
            }
            if (stack2.empty())
            {
                while (!stack1.empty()){
                    stack2.push(stack1.pop());
                }
            }    
            return stack2.pop();
        }
    }
     
    # -*- coding:utf-8 -*-
    class Solution:
        def __init__(self):
            self.stack1=[]
            self.stack2=[]
        def push(self, node):
            # write code here
            self.stack1.append(node)
        def pop(self):
            # return xx
            if len(self.stack2)>0:
                return self.stack2.pop()
            while self.stack1:
                self.stack2.append(self.stack1.pop())
            if len(self.stack2)>0:
                return self.stack2.pop()
  • 相关阅读:
    Cesium绘制一个旋转发光的四棱锥
    使用Nginx实现反向代理转载
    Nginx 代理本地文件夹
    WebGIS工程师的技能包
    nginx启动报错(1113: No mapping for the Unicode character exists in the target multibyte code page)
    Cesium动态扩散圆
    Billboard高度模式
    Nginx 配置问题 server directive is not allowed here in /etc/nginx/nginx.conf:69
    Nginx 安装(打开、关闭、重启)
    Cesium Primitive也可以设置贴地,通过外观设置
  • 原文地址:https://www.cnblogs.com/hrnn/p/13358671.html
Copyright © 2011-2022 走看看