实现两个栈模拟队列

实现两个栈模拟队列

思路:可以想象一下左手和右手,两个栈:stack1(数据所在的栈) ,stack2(临时存放)。
入队:需要将入队 num 加在 stack1 的栈顶即可;
出队:这个就会麻烦点,需要用到临时栈stack2。先将 stack1中的所有元素放到 stack2中,再把stack2的顶部元素弹出一个,再把 stack2中的元素放回到stack1中,切记!不要忘了把stack2中的元素放回到stack1中!!!

代码如下:

import java.util.Scanner;
import java.util.Stack;

/**
 * @author: Arbicoral
 * @Description: 两个栈模拟队列
 */
public class StackSimulateQueue {
    private static Stack<Integer> stack1 = new Stack<>();
    private static Stack<Integer> stack2 = new Stack<>();
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("请输入要入队列的数(以-1结束):");
        while (true){
            if (sc.hasNextInt()){
                int next = sc.nextInt();
                if (next == -1){
                    break;
                } else {
                    stack1.push(next);
                }
            }
        }

        // 测试
        StackSimulateQueue ssq = new StackSimulateQueue();
        ssq.print();// 打印当前队列中的值
        ssq.push(356);//入队
        ssq.poll();//出队
        ssq.print();
        ssq.poll();
        ssq.poll();
        ssq.print();
        ssq.poll();
        ssq.print();
        ssq.poll();
    }

    // 出队列:先把 stack1中的所有元素放到 stack2中,再把stack2的顶部元素弹出,还需要再把 stack2中的元素放回到stack1中
    public void poll(){
        if (stack1.isEmpty()){
            System.out.println("队列中空空如也~~");
        }
        while (!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        System.out.println("出队:" + stack2.pop());
        while (!stack2.isEmpty()){
            stack1.push(stack2.pop());
        }
    }

    // 入队列:需要将新添加的数据压入 stack1底部,即,先把 stack1 -> stack2,再把 num放到stack1,stack2 -> stack1
    // 入队列:直接放到 stack1顶部即可
    public void push(Integer num){
        System.out.println("入队:" + num);
        stack1.push(num);
    }

    // 打印当前队列
    // 注意:应该先将 stack1中的元素放到 stack2中,stack2弹出一个存一个,打印后放回 stack1中
    public void print(){
        System.out.print("当前队列中有:");
        while (!stack1.isEmpty()){
            stack2.push(stack1.pop());
        }
        // 放回stack1
        while (!stack2.isEmpty()){
            int temp = stack2.pop();
            System.out.print(temp + "\t");
            stack1.push(temp);
        }
        System.out.println();
    }
}

示例:

输入:12 32 53 67 2 5 7 -1
输出:
image.png

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值