剑指offer五之用两个栈实现队列

时间:2023-03-09 12:54:38
剑指offer五之用两个栈实现队列

一、题目

  用两个栈来实现一个队列,完成队列的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();
}
}

2、测试方法

public class TestMain {
public static void main(String[] args) {
int[] a={1,2,3,4,5}; Solution solution=new Solution(); for(int i=0;i<a.length;i++){
solution.push(a[i]); //push的顺序1 2 3 4 5
}
for(int j=0;j<a.length;j++){
int val= solution.pop();
System.out.print(val+" "); //pop的顺序 1 2 3 4 5
}
}
}

---------------------------------------------------------------------------------------------------------------------------------------------

参考链接:https://www.nowcoder.com/questionTerminal/54275ddae22f475981afa2244dd448c6