zoukankan      html  css  js  c++  java
  • Lintcode40-Implement Queue by Two Stacks-Medium

    40. Implement Queue by Two Stacks

    As the title described, you should only use two stacks to implement a queue's actions.

    The queue should support push(element)pop() and top() where pop is pop the first(a.k.a front) element in the queue.

    Both pop and top methods should return the value of first element.

    Example

    Input
    push(1)
    push(2)
    push(3)
    push(4)
    push(5)
    pop()
    pop()
    push(6)
    push(7)
    push(8)
    push(9)
    pop()
    pop()
    Expected
    [1,2,3,4]

    思路:

    用两个stack,实现一个queue。

    push到stack2。pop的时候,先判断stack1是否为空:如果不为空(说明上一轮push进stack1的,没有pop完),直接stack1.pop(); 如果为空,则把stack2所有元素全部push到stack1,(保证第一个push到stack2的元素最后push进stack1),再stack1.pop().

    注意:

    1. 创建两个类变量,在构造方法中初始化两个类变量stack1, stack2.
    2. 代码改进,line 17,18 和 line 26,27 重复,可以封装成一个方法。

    代码:

     1 public class MyQueue {
     2     Stack<Integer> stack1;
     3     Stack<Integer> stack2;
     4     
     5     public MyQueue() {
     6         stack1 = new Stack<Integer>();
     7         stack2 = new Stack<Integer>();
     8     }
     9     
    10     public void push(int element) {
    11         stack2.push(element);
    12     }
    13 
    14     
    15     public int pop() {
    16         if (stack1.isEmpty()) {
    17             while (!stack2.isEmpty()) {
    18                 stack1.push(stack2.pop());
    19             }
    20         }
    21         return stack1.pop();
    22     }
    23 
    24     public int top() {
    25         if (stack1.isEmpty()) {
    26             while (!stack2.isEmpty()) {
    27                 stack1.push(stack2.pop());
    28             }
    29         }
    30         return stack1.peek();
    31     }
    32 }

    代码改进:

    public class MyQueue {
        Stack<Integer> stack1;
        Stack<Integer> stack2;
        
        public MyQueue() {
            stack1 = new Stack<Integer>();
            stack2 = new Stack<Integer>();
        }
        
        public void stack2ToStack1(){
            while (!stack2.isEmpty()) {
                stack1.push(stack2.pop());
            }
        }
        
        public void push(int element) {
            stack2.push(element);
        }
    
        
        public int pop() {
            if (stack1.isEmpty()) {
                this.stack2ToStack1();
            }
            return stack1.pop();
        }
    
        public int top() {
            if (stack1.isEmpty()) {
                this.stack2ToStack1();
            }
            return stack1.peek();
        }
    }
  • 相关阅读:
    H5调用相机和相册更换头像
    二分查找的递归解法以及希尔排序
    递归----经典问题:汉诺塔游戏
    递归----基础训练
    位运算-实现加减乘除
    位运算-出现k次与出现一次
    位运算-将整数的二进制进行奇偶位互换
    位运算-二进制中1的个数(三种解法)
    位运算-查找数组中唯一成对的数
    小小的总结一下2018年
  • 原文地址:https://www.cnblogs.com/Jessiezyr/p/10651961.html
Copyright © 2011-2022 走看看