zoukankan      html  css  js  c++  java
  • LeetCode 232. Implement Queue using Stacks

    Implement the following operations of a queue using stacks.

    • push(x) -- Push element x to the back of queue.
    • pop() -- Removes the element from in front of queue.
    • peek() -- Get the front element.
    • empty() -- Return whether the queue is empty.

    Notes:

    • You must use only standard operations of a stack -- which means only push to toppeek/pop from topsize, and is empty operations are valid.
    • Depending on your language, stack may not be supported natively. You may simulate a stack by using a list or deque (double-ended queue), as long as you use only standard operations of a stack.
    • You may assume that all operations are valid (for example, no pop or peek operations will be called on an empty queue).

    题意:使用栈实现队列的如下操作:
    push(x):将x加入队尾
    pop():移除队首元素
    peek():取队首元素
    empty():判断队列是否为空
    Notes:
    只能使用栈的基本操作:push, pop ,peek, size, isEmpty


    思路:使用两个栈。
    元素出队时,先将栈stack1中除栈顶元素外的所有元素出栈,存入stack2中;移除栈顶元素(即队尾元素)后,再将stack2中的元素放入stack1中

    class MyQueue {
        Stack<Integer> stack1 = new Stack<>();
        Stack<Integer> stack2 = new Stack<>();
        private int top;
    
        /** Initialize your data structure here. */
        public MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            if(stack1.isEmpty())//stack1.size() == 0
                top = x;
            stack1.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            while(stack1.size() > 1){
                top = stack1.pop();
                stack2.push(top);
            }
            int x = stack1.pop();
            while(stack2.size() > 0){
                int i = stack2.pop();
                stack1.push(i);
            }
            return x;
        }
        
        /** Get the front element. */
        public int peek() {
            return top;
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
            return stack1.isEmpty();
        }
    }
  • 相关阅读:
    函数高阶(函数,改变函数this指向,高阶函数,闭包,递归)
    案例:新增数组方法
    案例:商品查询
    案例:forEach和some区别
    ES5新增方法(数组,字符串,对象)
    案例:借用父构造函数继承属性和方法
    构造函数 和 原型
    汽车小常识别让六大汽车驾驶软肋阻碍你
    Opencv 图像增强和亮度调整<6>
    C# StringBulider用法<1>
  • 原文地址:https://www.cnblogs.com/zeroingToOne/p/8570441.html
Copyright © 2011-2022 走看看