算法通关村-栈实现队列,队列实现栈解析

栈实现队列

可以准备两个栈,栈A和栈B。栈A进行入栈操作。出栈时,判断栈B是否为空,为空就将栈A的元素遍历取出,放入栈B。此时栈B顶端元素就是最先进来的元素,此时peek和pop操作就在栈B进行。判断整体队列是否为空,两个栈同时判断是否为空,代码如下

public class StackToQueue {
    Deque<Integer> inStack = new LinkedList<>();
    Deque<Integer> outStack = new LinkedList<>();


    public void push(int data){
        inStack.push(data);
    }

    public int pop(){
        if (outStack.isEmpty()){
            intToOut();
        }
        return outStack.pop();
    }

    public int peek(){
        if (outStack.isEmpty()){
            intToOut();
        }
        return outStack.peek();
    }

    public boolean empty(){
        return inStack.isEmpty() && outStack.isEmpty();
    }

    public void intToOut(){
        while (!inStack.isEmpty()){
            outStack.push(inStack.pop());
        }
    }

    public static void main(String[] args) {
        StackToQueue stackToQueue = new StackToQueue();
        stackToQueue.push(2);
        stackToQueue.push(3);
        stackToQueue.push(4);
        stackToQueue.push(5);
        System.out.println(stackToQueue.peek());
        stackToQueue.pop();
        System.out.println(stackToQueue.peek());
        stackToQueue.pop();
        System.out.println(stackToQueue.peek());
        System.out.println(stackToQueue.empty());
    }

队列实现栈

队列实现栈,创建两个队列queue1和queue2,queue1时主要存储数据元素的队列,queue2时辅助队列。添加元素时,将元素添加到queue2,然后再将queue1所有元素添加到queue2,最后queue1和queue2相互交换。此时,最新添加的元素就在queue1的队列头部,实现栈的结构。代码如下:

public class QueueToStack {
    Queue<Integer> queue1 = new LinkedList<>();
    Queue<Integer> queue2 = new LinkedList<>();

    public void push(int data){
        queue2.add(data);
        while (!queue1.isEmpty()){
            queue2.add(queue1.poll());
        }
        Queue<Integer> tempQueue = queue1;
        queue1 = queue2;
        queue2 = tempQueue;
    }

    public int peek(){
        return queue1.peek();
    }

    public int pop(){
        return queue1.poll();
    }

    public boolean empty(){
        return queue1.isEmpty();
    }

    public static void main(String[] args) {
        QueueToStack queueToStack = new QueueToStack();
        queueToStack.push(1);
        queueToStack.push(2);
        queueToStack.push(3);
        System.out.println(queueToStack.peek());
        queueToStack.pop();
        System.out.println(queueToStack.peek());

    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值