zoukankan      html  css  js  c++  java
  • 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();
        }
    }
    
  • 相关阅读:
    正则学习笔记 主要是C#或Javascript
    禁止页面复制、保存等常用js命令
    Webkit几个CSS效果和JS控制
    marquee用法的详细解释让文字动起来
    js比较两个时间的大小
    关于System.MissingMethodException
    Windows mobile XmlTextWriter FileStream 路径问题
    jQuery UI插件sortable中文帮助文档
    asp.net中用Eval绑定时间的格式
    jQuery图表插件Flot
  • 原文地址:https://www.cnblogs.com/wxisme/p/4688224.html
Copyright © 2011-2022 走看看