Java练习(二十七):用两个栈来模拟队列

1. 要求:

借助两个栈来实现一个队列的功能,完成队列的Push和Pop操作。

输出的数组顺序,跟输入进程序的数组顺序一致。

2. 示例代码:

//借助两个栈来实现一个队列的功能,完成队列的Push和Pop操作。 输出的数组顺序,跟输入进程序的数组顺序一致。

package TwoStackDemo;
 
import java.util.Stack;
 
public class TwoStackAsQueue {
    static Stack<Integer> stack1 = new Stack<Integer>();
    static Stack<Integer> stack2 = new Stack<Integer>();
 
    //入栈操作:逐个数据放入stack1栈中
    public void push(int node){
        stack1.push(node);
    }
 
    //出栈操作:将stack1栈中所有的元素一次性全部出栈后入栈至stack2,然后从stack2中模拟队列的出栈操作
    //每调用一次pop()方法,stack2中出栈一个元素
    public int pop(){
        //如果stack2空,则先将stack1所有元素出栈,逐个放进stack2中
        if(stack2.isEmpty()){
            while (!stack1.isEmpty()){
                stack2.push(stack1.pop()); //此处是栈类自带的pop方法
                System.out.println("---stack2入栈---");
                System.out.println(stack2);
            }
            return stack2.pop(); //此处是栈类自带的pop方法,从stack2弹出一个值
        } else {        //如果调用该方法时,stack2不为空,即stack1所有元素已经入stack2, 此时直接弹出stack2最上面的值即可
            return stack2.pop();
        }
    }
 
    public static void main(String[] args) {
        TwoStackAsQueue twoStackAsQueue = new TwoStackAsQueue();
        int[] nums = {6,2,5,4,8};
        //数据入栈stack1
        for(int i=0; i<nums.length; i++){
            twoStackAsQueue.push(nums[i]);
            System.out.println("---stack1入栈---");
            System.out.println(stack1);
        }
        System.out.println("*************************************************************");
 
        //出栈
        for(int i=0; i<nums.length; i++){
            Integer out = twoStackAsQueue.pop();
            System.out.println("---stack2出栈---");
            System.out.println(stack2);
            System.out.println("此次出栈的值: " +out);
        }
    }
 
}

3. 运行结果:

---stack1入栈---
[6]
---stack1入栈---
[6, 2]
---stack1入栈---
[6, 2, 5]
---stack1入栈---
[6, 2, 5, 4]
---stack1入栈---
[6, 2, 5, 4, 8]
*************************************************************
---stack2入栈---
[8]
---stack2入栈---
[8, 4]
---stack2入栈---
[8, 4, 5]
---stack2入栈---
[8, 4, 5, 2]
---stack2入栈---
[8, 4, 5, 2, 6]
---stack2出栈---
[8, 4, 5, 2]
此次出栈的值: 6
---stack2出栈---
[8, 4, 5]
此次出栈的值: 2
---stack2出栈---
[8, 4]
此次出栈的值: 5
---stack2出栈---
[8]
此次出栈的值: 4
---stack2出栈---
[]
此次出栈的值: 8

Process finished with exit code 0

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值