队列实现栈&栈实现队列

这篇博客展示了如何利用Java编程语言,通过两个队列巧妙地实现一个栈的功能,以及如何利用两个栈来实现队列的操作。文中给出了详细的代码实现,包括pushStack、popStack、pushQueue和popQueue等方法,演示了数据结构的灵活运用。
摘要由CSDN通过智能技术生成

在数据结构中,可以使用两个队列实现一个栈,也可以使用两个栈实现一个队列,代码实现如下:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;


public class Practice {
    //两个队列实现一个栈
    private static Queue<Integer> queue1 = new LinkedList<>();
    private static Queue<Integer> queue2 = new LinkedList<>();
    public static void pushStack(int value){
        if(queue1.isEmpty() && queue2.isEmpty()){
            queue1.add(value);
        }else if(queue1.isEmpty()){
            queue2.add(value);
        }else if(queue2.isEmpty()){
            queue1.add(value);
        }
    }

    public static int popStack(){
        Queue<Integer> popQueue = queue1.isEmpty() ? queue2 : queue1;
        Queue<Integer> pushQueue = queue1.isEmpty() ? queue1 : queue2;
        while(popQueue.size() > 1){
            pushQueue.add(popQueue.remove());
        }
        return popQueue.remove();
    }

    //两个栈实现一个队列
    private static Stack<Integer> stack1 = new Stack<>();
    private static Stack<Integer> stack2 = new Stack<>();

    public static void pushQueue(int value){
        stack1.push(value);
    }

    public static int popQueue(){
        if(stack1.isEmpty() && stack2.isEmpty()){
            throw new UnsupportedOperationException("the queue is empty");
        }
        if(stack2.isEmpty()){
            while(!stack1.isEmpty()){
                stack2.push(stack1.pop());
            }
        }
        return stack2.pop();
    }

    public static void main(String[] args) {
        pushQueue(10);
        pushQueue(20);
        pushQueue(30);
        pushQueue(40);
        System.out.println(popQueue());
        System.out.println(popQueue());
        System.out.println(popQueue());
        pushQueue(50);
        pushQueue(60);
        System.out.println(popQueue());
        System.out.println(popQueue());
        System.out.println(popQueue());
        
		System.out.println();

        pushStack(10);
        pushStack(20);
        pushStack(30);
        System.out.println(popStack());
        pushStack(40);
        pushStack(50);
        System.out.println(popStack());
        System.out.println(popStack());
    }
}

运行结果:

10
20
30
40
50
60

30
50
40
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值