zoukankan      html  css  js  c++  java
  • 化栈为队列

    此博客链接:https://www.cnblogs.com/ping2yingshi/p/12800611.html

    化栈为队列(52min)

    题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks-lcci/

    实现一个MyQueue类,该类用两个栈来实现一个队列。


    示例:

    MyQueue queue = new MyQueue();

    queue.push(1);
    queue.push(2);
    queue.peek(); // 返回 1
    queue.pop(); // 返回 1
    queue.empty(); // 返回 false

    题解:

            思路:

                     1.用两个栈,一个栈stack1装满后,进入另外一个栈stack2,stack2中的元素读取顺序和队列是一致的。

                     2队列初始化时,先初始化两个栈。

                     3.队列元素入队和栈元素入栈操作一样。

                     4.取队头元素时,先判断stack2是否为空,不为空时,取栈顶元素即为队头元素,stack2为空时,把stack1中的元素入栈到stack2中,然后在取stack2的栈顶元素。

                     5.当两个栈都为空时,队列才为空。

                     6.删除队头元素时,需要先取出队头元素,然后在删除队头元素。

    注意:先完成判断队列是否为空和取出队头元素然后在完成删除队列头节点。

    代码如下:

    class MyQueue {
        Stack<Integer> stack1;
        Stack<Integer> stack2;
    
        /** Initialize your data structure here. */
        public MyQueue() {
        stack1=new Stack<Integer>();
         stack2=new Stack<Integer>();
        }
        
        /** Push element x to the back of queue. */
        public void push(int x) {
            stack1.push(x);
        }
        
        /** Removes the element from in front of queue and returns that element. */
        public int pop() {
            peek();
            return stack2.pop();
    
    
        }
        
        /** Get the front element. */
        public int peek() {
          if(stack2.empty()==false)
            return   stack2.peek();
           else
           {
               while(stack1.isEmpty()==false)
                  stack2.push(stack1.pop());
                 return stack2.peek();
           }
         
             
        }
        
        /** Returns whether the queue is empty. */
        public boolean empty() {
           return stack1.isEmpty()&&stack2.isEmpty(); 
    
        }
    }
  • 相关阅读:
    字典树+二叉树
    ##22
    简单代码优雅写
    全排列
    【持续更新】哟!又在写BUG啊!
    大整数加法和大整数乘法
    【框架编程思想】线数筛的高级应用(欧拉12题和欧拉21题)
    【持续更新】 用算法流程实现的代码块们
    记忆化
    资源收集
  • 原文地址:https://www.cnblogs.com/ping2yingshi/p/12800611.html
Copyright © 2011-2022 走看看