一、题目

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

二、思路

      1、Push操作:将数据直接压入stack1即可

      2、Pop操作:将stack1中的数据全部弹出压入到stack2中,然后将stack1中的数据全部弹出即可

      注意:要将stack1中的数据全部压入到stack2中后,才能将stack2中的数据弹出

三、代码 

1、解决方法

import java.util.Stack;

public class Solution {

    Stack<Integer> stack1 = new Stack<Integer>();//栈1
    Stack<Integer> stack2 = new Stack<Integer>();//栈2

    public void push(int node) { //push操作
        stack1.push(node);
    }

    public int pop() {  //pop操作
        if (stack1.empty() && stack2.empty()) {
            throw new RuntimeException("Queue is empty!");
        }
        if (stack2.empty()) {
            while (!stack1.empty()) {
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}
View Code

相关文章:

  • 2022-02-24
  • 2021-08-21
  • 2021-08-30
  • 2022-02-02
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
猜你喜欢
  • 2021-12-29
  • 2021-12-30
  • 2021-12-23
  • 2022-01-03
  • 2021-09-22
  • 2021-08-10
  • 2022-01-17
相关资源
相似解决方案