每天一道算法题——用两个栈实现队列和用两个队列实现栈

1.用两个栈实现队列

题目描述

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

测试用例:

[“PSH1”,”PSH2”,”PSH3”,”POP”,”POP”,”PSH4”,”POP”,”PSH5”,”POP”,”POP”]

对应输出应该为:

1,2,3,4,5

源码:

import java.util.Stack;

public class Test1 {
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();

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

    public int pop() {
        if (stack2.isEmpty()) {
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }
}

运行时间
16ms

2.用两个队列实现栈

题目描述

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

分析:
入栈:将元素进队列q1
出栈:判断队列q1中元素的个数是否为1,如果等于1,则出队列,否则将队列q1中的元素 以此出队列并放入队列q2,直到队列q1中的元素留下一个,然后队列q1出队列,再把 队列q2中的元素出队列以此放入队列q1中。
也就是说把非空队列的n-1个压人空对列,剩的第n个出队…即总有一个队列为空。

import java.util.ArrayDeque;
import java.util.Queue;

public class Test1 {

    Queue<Integer> q1 = new ArrayDeque<Integer>();
    Queue<Integer> q2 = new ArrayDeque<Integer>();

    public void push(int node) {
        if(q1.isEmpty()){
            q2.offer(node);
        }else{
        q1.offer(node);
        }
    }

    public int pop() {
        if (q2.isEmpty()&&!q1.isEmpty()) {
            return swapQueue(q2, q1);
        }else if (q1.isEmpty()&&!q2.isEmpty()) {
            return swapQueue(q1, q2);
        }
        return -1;
    }
    private int swapQueue(Queue<Integer> q1,Queue<Integer> q2) {
        while(q2.size()!=1){
            q1.offer(q2.poll());
        }
        return q2.poll();
    }
}

此处有一个易错点

public class TestMain {
    public static void main(String[] args) {
        Test1 test1 = new Test1();
        test1.push(1);
        test1.push(2);
        test1.push(3);
        test1.push(4);
        test1.push(5);
        Integer i = null;  //注意此处设置一个额外的变量,是因为如果直接
        // System.out.println(test1.pop())的话,会再进行一次出栈的操作的。

        while ( (i = test1.pop()) != -1){  
            System.out.println(i);
        }       
    }
}

另外,此处可以将方法pop()的返回值改为Integer,这样可以直接return null。就避免了存储-1的尴尬情景了。
即:

public Integer pop() {
        if (q2.isEmpty()&&!q1.isEmpty()) {
            return swapQueue(q2, q1);
        }else if (q1.isEmpty()&&!q2.isEmpty()) {
            return swapQueue(q1, q2);
        }
        return null;
    }

运行时间:
6ms

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值