数据结构----Java中栈与队列相互实现

本文探讨了如何使用两个队列来模拟栈的先进后出特性,以及如何利用两个栈实现队列的先进先出(FIFO)原则。通过这种方式,可以加深对数据结构中栈和队列理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈:先进后出;队列:先进先出,FIFO

利用两个队列实现栈的功能

//利用两个队列实现栈
import java.util.Queue;
import java.util.LinkedList;

public class QueueToStack{
    Queue<Integer> queue1 = new LinkedList<Integer>();
    Queue<Integer> queue2 = new LinkedList<Integer>();
    
    //队列模拟进栈
    public static void push(int item){
        if(queue1.isEmpty() && queue2.isEmpty()){
            queue1.add(item);
            return;
        }
        if(queue1.isEmpty()){
            queue2.add(item);
            return;
        }
        if(queue2.isEmpty()){
            queue1.add(item);
            return;
        }    
    }
    
    //队列模拟出栈
    public static int pop(){
        if(queue1.isEmpty() && queue2.isEmpty()){
            try{
                throw new Exception("栈为空");
            }catch(Exception e){
                e.printStackTrace();
            }
        }    
        if(queue1.isEmpty()){
            while(queue2.size() > 1){
                queue1.add(queue2.poll());
            }
            return queue2.poll();
        }
        if(queue2.isEmpty()){
            while(queue1.size() > 1){
                queue2.add(queue1.poll());
            }
            return queue1.poll();
        }
        return 0;
    }
}

利用两个栈实现队列的功能

//利用两个栈实现队列的功能
import java.util.Stack;
public class StackToQueue{
    Stack<Integer> stack1 = new Stack<Integer>();
    Stack<Integer> stack2 = new Stack<Integer>();
    
    //栈实现元素进队列
    public static void add(int item){
        if(stack1.isEmpty() && stack2.isEmpty()){
            stack1.push(item);
            return;
        }
        if(stack1.isEmpty()){
            stack2.push(item);
            return;
        }
        if(stack2.isEmpty()){
            stack1.push(item);
            return;
        }
    }

    //栈实现元素出队列
    public static void poll(){
        if(stack1.isEmpty() && stack2.isEmpty()){
            try{
                throw new Exception("队列为空");
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        if(stack1.isEmpty()){
            while(stack2.size() > 1){
                stack1.push(stack2.pop());
            }
            return stack2.pop();
        }
        if(stack2.isEmpty()){
            while(stack1.size() > 1){
                stack2.push(stack1.pop());
            }
            return stack1.pop();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值