编程题:用两个栈实现队列,支持队列的基本操作

本文介绍了一种使用两个栈来实现队列的方法,通过将元素添加到第一个栈中,然后在需要时转移到第二个栈来模拟队列的先进先出特性。文章详细解释了如何在Java中实现这一算法,并提供了完整的代码示例。

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

题目要求:

用两个栈实现队列,支持队列的基本操作

CODE

import java.util.*;

public class Main{
    
    public static void main(String[] args){
        QueueByStack sq = new QueueByStack();
        Scanner scanner = new Scanner(System.in);
        int N = Integer.valueOf(scanner.nextLine());
        for(int i=0;i<N;i++){
            String line = scanner.nextLine();
            if(line.startsWith("add")){
                String[] num = line.split(" ");
                int x =Integer.valueOf(num[1]);
                sq.add(x);
            }else if(line.startsWith("poll")){
                sq.poll();
            }
            else if(line.startsWith("peek")){
                int res = sq.peek();
                System.out.println(res);
            }
        }
        
        
    }
}

class QueueByStack{
    public Stack<Integer> s1;
    public Stack<Integer> s2;
    
    public QueueByStack(){
        this.s1 = new Stack<Integer>();
        this.s2 = new Stack<Integer>();
    }
    
    public void add(int  x){
        s1.push(x);
    }
    public Integer poll(){
        if(!s2.isEmpty()){
            return s2.pop();
        }else{
            while(!s1.isEmpty()){
                s2.push(s1.pop());
            }
            return s2.pop();
        }
    }
    public Integer peek(){
         if(!s2.isEmpty()){
            return s2.peek();
        }else{
            while(!s1.isEmpty()){
                s2.push(s1.pop());
            }
            return s2.peek();
        }
    }
    
}

KEYPOIT

用2个栈,S1和S2

  • 加:往S1里加
  • poll:
    • 如果S2不为空,直接操作S2,因为S2都是老的;
    • 如果S2为空,则得把S1的元素整S2里,这样从S2出正好是队列的出了
  • peek:同S2

!!!Stack是pop(), Queue是poll()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值