zoukankan      html  css  js  c++  java
  • 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).

     思路:想要使用堆栈实现队列,堆栈出一个再进一个相当于没进没出,所以我们采用两个堆栈实现队列,先进第一个堆栈,再把第一个堆栈的元素依次给另外一个堆栈,那么即将要进来的元素就到了第一个堆栈的栈底,刚好,再从堆栈2到堆栈1,和队列的顺序就保持一致了。

    public class MyQueue {    Stack<Integer>stack1=new Stack<>();    Stack<Integer>stack2=new Stack<>    /** Initialize your data structure here. */

        public MyQueue() {
            
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            while(!stack1.isEmpty())
            {
            	stack2.push(stack1.pop());//堆栈1的元素依次给堆栈2
            }
            stack1.push(x);//x就成了1的栈底元素
    while(!stack2.isEmpty()) { stack1.push(stack2.pop());//再把2给1 } } /** Removes the element from in front of queue and returns that element. */ public int pop() { return stack1.pop();//栈顶元素就是队列的第一个元素 } /** Get the front element. */ public int peek() { return stack1.peek(); } /** Returns whether the queue is empty. */ public boolean empty() { return stack1.isEmpty(); } }

      堆栈和队列之间的转换和巧妙,大家可以尝试一下!

  • 相关阅读:
    蓝牙4.0BLE cc2540 cc2541 ios OAD课程(空中固件升级)[原版的,多图]
    ASP.NET文件上传和下载
    onethink和phpwind共享
    折返(Reentrancy)VS线程安全(Thread safety)
    使用更清晰DebugLog开发和调试工具
    MySql分析算法作品索引(马上,只是说说而已B-tree)
    使用shell命令分析统计日志
    刷牙LeetCode思考
    Cocos3d-x 发布第一版
    SSH连接Linux的Server超时
  • 原文地址:https://www.cnblogs.com/zhangfanxmian/p/6929970.html
Copyright © 2011-2022 走看看