面试必考03——队列实现栈,栈实现队列

队列实现栈

  • 图的深度优先遍历需要用栈来实现。
  • 用队列实现图的深度优先遍历方法是:先用队列实现栈结构,再用栈结构实现图的深度优先遍历。
  • 代码思路:构建两个队列:Data队列和help队列;压入数据时数据都进Data队列,假设队列中按顺序进入了1,2,3,4,5,返回数据时,把1,2,3,4 放入help队列,然后拿出Data中的5返回;接着改引用,将Data队列和help队列的引用交换;下次返回数据时就依然是把Data队列中的123放入help队列,然后拿出Data队列中的4返回,再交换两队列的引用,如此反复。
import java.util.LinkedList;
import java.util.Queue;

public class T02QueueToStack {
    private Queue<Integer> queue;
    private Queue<Integer> help;

    public T02QueueToStack() {
        queue = new LinkedList<>();
        help = new LinkedList<>();
    }

    public void push(Integer e) {
        queue.add(e);
    }

    public int pop() {
        if (queue.isEmpty()) {
            throw new RuntimeException("empty");
        }
        while (queue.size() != 1) {
            help.add(queue.poll());
        }
        int res = queue.poll();
        swap();
        return res;
    }

    public int peek() {
        if (queue.isEmpty()) {
            throw new RuntimeException("empty");
        }
        while (queue.size() != 1) {
            help.add(queue.poll());
        }
        int res = queue.poll();
        help.add(res);
        swap();
        return res;
    }

    public void swap() {
        Queue<Integer> tmp = queue;
        queue = help;
        help = tmp;
    }
}

栈实现队列

  • 思路:构建两个栈:Push栈和Pop栈;将Push栈中的数据倒入Pop栈中然后返回给用户,就实现了队列。需要注意两个条件:①Pop栈为空时才能其中倒入数据。②向Pop栈倒入数据时必须要倒完。
  • 固定栈1入队,栈2出队。pop() 操作时,①如果两栈都为空,报异常;②如果出队栈有元素就出队;③如果出队栈为空,就把入队栈的元素都弹过来再出队。
import java.util.Stack;

public class T01StackToQueue {

    private Stack<Integer> s1;
    private Stack<Integer> s2;

    public T01StackToQueue() {
        s1 = new Stack<>();
        s2 = new Stack<>();
    }

    public void add(int obj) {
        s1.push(obj);
    }

    public Integer poll() {
        if (s1.isEmpty() && s2.isEmpty()) {
            throw new RuntimeException("empty");
        }
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.pop();
    }

    public Integer peek() {
        if (s1.isEmpty() && s2.isEmpty()) {
            throw new RuntimeException("empty");
        }
        if (s2.isEmpty()) {
            while (!s1.isEmpty()) {
                s2.push(s1.pop());
            }
        }
        return s2.peek();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值