java实现两个栈模拟实现队列出队

题目描述:

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

输入:

每个输入文件包含一个测试样例。
对于每个测试样例,第一行输入一个n(1<=n<=100000),代表队列操作的个数。
接下来的n行,每行输入一个队列操作:
1. PUSH X 向队列中push一个整数x(x>=0)
2. POP 从队列中pop一个数。

输出:

对应每个测试案例,打印所有pop操作中从队列pop中的数字。如果执行pop操作时,队列为空,则打印-1。

样例输入:
3
PUSH 10
POP
POP
样例输出:
10
-1
源代码如下:

package com.lb.test;
import java.util.Scanner;
import java.util.Stack;
public class SimulationQueue {
    static Stack<Integer> stack1 = new Stack<Integer>();
    static Stack<Integer> stack2 = new Stack<Integer>();
    public static void main(String[] args) {
        StringBuffer sb = new StringBuffer();
        int count=0;
        @SuppressWarnings("resource")
        Scanner in = new Scanner(System.in);
        count = in.nextInt();
        do{
            String input = in.nextLine();
            sb.append(input);
            --count;
            sb.append("#");
        }while(count>=0);
        testQueue(sb);
    }

    private static void testQueue(StringBuffer sb) {
        String []instruction = sb.toString().split("\\#");
        for(int i = 1;i<instruction.length;++i){
            if(instruction[i].contains(" ")){
                String [] queueHandle = instruction[i].split(" ");
                @SuppressWarnings("unused")
                int result = QueueHandle(queueHandle[0],queueHandle[1]);
            }else{
                int result = QueueHandle(instruction[i],"");
                System.out.println(result);
            }
        }
    }
    /*
     * 两个栈模拟一个队列,首先初始两个栈都为空,当有push操作时,先往stack1中加入一个元素,出队列(pop)的时候依次从stack1中取出
     * 元素放入stack2中,然后把栈的第一个元素弹出,然后再把stack2中的元素假如stack1中,并且stack2中元素为空。
     *
     */
    private static int QueueHandle(String instruction, String value) {
        Integer popValue =0;
        if(instruction.equals("push")||instruction.equals("PUSH")){
            int pushValue = Integer.parseInt(value);
            stack1.add(pushValue);
            /*
             * 执行入队列操作
             */
        }else{
            /**
             * stack1中的所有元素出栈放入stack2中
             */
            while(!stack1.empty()){
                stack2.add(stack1.pop());
            }
            /*
             * 出队列操作,如果为空,直接返回-1
             */
            if(stack2.size()==0){
                return -1;
            }else{
                 popValue = stack2.pop();
            }
            while(!stack2.empty()){
                stack1.add(stack2.pop());
            }
        }
        return popValue;
    }
}



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值