zoukankan      html  css  js  c++  java
  • Leetcode232.用堆栈实现队列

    使用栈实现队列的下列操作:

    push(x) -- 将一个元素放入队列的尾部。
    pop() -- 从队列首部移除元素。
    peek() -- 返回队列首部的元素。
    empty() -- 返回队列是否为空。

    链接:https://leetcode-cn.com/problems/implement-queue-using-stacks
    思路:入栈的时候 还是正常入栈,出栈的时候将所有的输入栈里面的东西输出 压到输出栈里面,然后再输出

    class MyQueue {
        Stack<Integer> S1;
        Stack<Integer> S2;
    
        /** Initialize your data structure here. */
        public MyQueue() {
            S1=new Stack<>();
            S2=new Stack<>();
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            S1.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            while(S2.isEmpty())//如果输出栈为空
            {
                while(!S1.isEmpty())
                {
                    S2.push(S1.pop());      //把输入栈的全部放入输出栈
                }
                
            }
            return S2.pop();
        }
        
        /** Get the front element. */
        public int peek() {
            while(S2.isEmpty())//如果输出栈为空
            {
                while(!S1.isEmpty())
                {
                    S2.push(S1.pop());      //把输入栈的全部放入输出栈
                }
                
            }
            return S2.peek();
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return S1.isEmpty() && S2.isEmpty();
        }
    }
    
    /**
     * 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();
     * boolean param_4 = obj.empty();
     */
  • 相关阅读:
    $.each
    KBASP.NET 2.0 網站部署的變革
    详尽解析window.event对象
    Jquery1.2.6 源码分析
    索引学习2聚族索引、非聚族索引、组合索引
    在C#中使用WIA获取扫描仪数据
    Adobe Photoshop CS5简体中文版+完美破解方法
    j2me开发图片加载
    数据库操作
    WPF之DataGrid应用
  • 原文地址:https://www.cnblogs.com/William-xh/p/13778402.html
Copyright © 2011-2022 走看看