描述

用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。

 

解析

其实就是将栈的先进后出,变为队列的先进先出。

stack1用来入栈。当push stack1时,将stack1的所有元素放到stack2,直到stack1为空。再将新值push进去,再将stack2的所有值再push回来到stack1。

 

代码

 

import java.util.Stack;

public class Solution {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    public void push(int node) {
        if (stack1.isEmpty()) {
            stack1.push(node);
        } else {
            while (!stack1.isEmpty()) {
                stack2.push(stack1.pop());
            }
            stack1.push(node);
            while (!stack2.isEmpty()) {
                stack1.push(stack2.pop());
            }
        }
    }
    
    public int pop() {
        //这里注意下返回值为null的情况,不能转为int
        return stack1.pop();
    }
}

 

相关文章:

  • 2022-12-23
  • 2021-12-28
  • 2021-06-22
  • 2021-05-07
  • 2022-12-23
  • 2021-08-22
  • 2021-08-23
猜你喜欢
  • 2021-09-15
  • 2021-05-31
  • 2021-05-23
  • 2022-12-23
  • 2021-07-31
  • 2021-11-08
相关资源
相似解决方案