zoukankan      html  css  js  c++  java
  • leetcode

    使用栈实现队列的特性

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

    push(x) -- 将一个元素放入队列的尾部。
    pop() -- 从队列首部移除元素。
    peek() -- 返回队列首部的元素。
    empty() -- 返回队列是否为空。
    示例:
        
    ```
    MyQueue queue = new MyQueue();
        
    queue.push(1);
    queue.push(2);  
    queue.peek();  // 返回 1
    queue.pop();   // 返回 1
    queue.empty(); // 返回 false
    ```
    
    说明:
    
    你只能使用标准的栈操作 -- 也就是只有 push to top, peek/pop from top, size, 和 is empty 操作是合法的。
    你所使用的语言也许不支持栈。你可以使用 list 或者 deque(双端队列)来模拟一个栈,只要是标准的栈操作即可。
    假设所有操作都是有效的 (例如,一个空的队列不会调用 pop 或者 peek 操作)。
    
    
    ```
    private Stack<Integer> in = new Stack<>();
    private Stack<Integer> out = new Stack<>();
    public static void main(String[] args) {
        // 使用栈实现队列的特性
        // 栈的特性是FILO, 队列的特性是FIFO, 所以使用栈实现队列的特性就需要使用两个栈来实现
        // 执行用时 :57 ms, 在所有 java 提交中击败了80.70%的用户
        //内存消耗 :34.1 MB, 在所有 java 提交中击败了53.06%的用户
        StackDemo obj = new StackDemo();
        obj.push(1);
        obj.push(2);
        System.out.println(obj.peek());
        System.out.println(obj.pop());
        System.out.println(obj.empty());
    }
    
    /** Initialize your data structure here. */
    public StackDemo() {
    
    }
    
    /** Push element x to the back of queue. */
    public void push(int x) {
        in.push(x);
    }
    
    /** Removes the element from in front of queue and returns that element. */
    public int pop() {
        if(out.isEmpty()) {
            while(!in.isEmpty()) {
                out.push(in.pop());
            }
        }
        return out.pop();
    }
    
    /** Get the front element. */
    public int peek() {
        if(out.isEmpty()) {
            while(!in.isEmpty()) {
                out.push(in.pop());
            }
        }
        return out.peek();
    }
    
    /** Returns whether the queue is empty. */
    public boolean empty() {
        return out.isEmpty() && in.isEmpty();
    }
    ```
  • 相关阅读:
    Codeforces Beta Round #9 (Div. 2 Only) C. Hexadecimal's Numbers dfs
    Codeforces Beta Round #9 (Div. 2 Only) B. Running Student 水题
    Codeforces Beta Round #9 (Div. 2 Only) A. Die Roll 水题
    51nod 1035 最长的循环节 数学
    BSGS 模板
    51nod 1040 最大公约数之和 欧拉函数
    51NOD 1179 最大的最大公约数 筛法
    BZOJ 2818: Gcd 筛法
    川大校赛总结
    SCOJ 4484 The Graver Robbers' Chronicles 后缀自动机
  • 原文地址:https://www.cnblogs.com/wadmwz/p/11750249.html
Copyright © 2011-2022 走看看