• LeetCode——Implement Queue using Stacks


    Description:

    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 top, peek/pop from top, size, 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).

    用栈来实现队列的功能。类似的还有用队列实现栈的功能。

    思路:栈和队列对数据的处理是不同的。栈是先进后出(FILO)队列是先进先出(FIFO)。所以要用两个栈来维护一个队列。一个数据栈,一个暂存数据栈。数据栈用来存储数据,暂存数据栈用来把数据栈中的数据首尾交换,模拟队列的数据操作。

    代码:

    class MyQueue {
        Stack<Integer> stack1;
        Stack<Integer> stack2;
        
        public MyQueue() {
            stack1 = new Stack();
            stack2 = new Stack();
        }
        
        // Push element x to the back of queue.
        public void push(int x) {
            stack1.push(x);
        }
    
        // Removes the element from in front of queue.
        public void pop() {
            //把栈中的元素移到另一个栈中,首尾倒序。
            while(!stack1.empty()) {
                stack2.push(stack1.pop());
            }
            //移除堆首元素。
            stack2.pop();
            //还原数据队列。
            while(!stack2.empty()) {
                stack1.push(stack2.pop());
            }
        }
    
        // Get the front element.
        public int peek() {
            //把栈中的元素移到另一个栈中,首尾倒序。
            while(!stack1.empty()) {
                stack2.push(stack1.pop());
            }
            //获取堆首元素。
            int front = stack2.peek();
            //还原数据队列。
            while(!stack2.empty()) {
                stack1.push(stack2.pop());
            }
            return front;
        }
    
        // Return whether the queue is empty.
        public boolean empty() {
            return stack1.empty();
        }
    }
    
  • 相关阅读:
    解决方案E: Unable to locate package ros-kinetic-rgbd-launch
    记一件无聊但有意思的小事
    硬件开发相关工具、名词备忘
    Verilog代码规范(持续更新)
    GIT简单使用——多人协作篇
    GIT简单使用——私人库篇
    调试Scrapy过程中的心得体会
    Selenium学习(三)Selenium总是崩溃的解决办法
    Selenium学习(二)入门小例子
    Selenium学习(一)环境搭建
  • 原文地址:https://www.cnblogs.com/wxisme/p/4688224.html
Copyright © 2020-2023  润新知