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()
  • 相关阅读:
    用iptables封杀内网的bt软件
    FreeBSD 利用IPFW实现限制局域网使用QQ
    网络安全设备Bypass功能介绍及分析
    活用Windows Server 2008系统的几种安全功能
    恢复mysql管理员密码
    远程控制Windows2003下安装Pcanywhere导致Awgina.dll出错的解决办法
    Ubuntu 11.04 LAMP+JSP环境安装过程
    hbase首次导入大批次的数据成功!
    Chubby是什么?
    DP-Triangle
  • 原文地址:https://www.cnblogs.com/hrnn/p/13358671.html
Copyright © 2011-2022 走看看