zoukankan      html  css  js  c++  java
  • NC76 用两个栈实现队列

    package NC;

    import java.util.*;

    /**
    * NC76 用两个栈实现队列
    *
    * 用两个栈来实现一个队列,完成 n 次在队列尾部插入整数(push)和在队列头部删除整数(pop)的功能。
    * 队列中的元素为int类型。保证操作合法,即保证pop操作时队列内已有元素。
    * 要求:空间复杂度 O(n) ,时间复杂度O(1)
    * @author Tang
    * @date 2021/9/26
    */
    public class Queue {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

    public void push(int node) {
    while(!stack2.isEmpty()) {
    stack1.push(stack2.pop());
    }
    stack1.push(node);
    }

    public int pop() {
    while(!stack1.isEmpty()) {
    stack2.push(stack1.pop());
    }
    if(stack2.isEmpty()) {
    return 0;
    }
    return stack2.pop();
    }

    public static void main(String[] args) {

    Queue queue = new Queue();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
    System.out.println(queue.pop());

    }

    }
  • 相关阅读:
    超级迷宫我的计划表
    不敢死队
    Let the Balloon Rise
    Hangover
    汉诺塔系列2
    Tri Tiling(递推)
    Tiling(递推,高精度)
    Color Me Less
    I Think I Need a Houseboat(圆计算)
    Kbased Numbers(递推)
  • 原文地址:https://www.cnblogs.com/ttaall/p/15339980.html
Copyright © 2011-2022 走看看