栈和队列的面试题Java实现

参看博客:http://www.imooc.com/article/1515

但是代码在两个队列实现一个栈的时候代码存在问题

正确代码如下:

复制代码
import java.util.Queue;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

public class Myqueue {

    private Queue<Integer>  queue1 = new LinkedBlockingQueue<>() ;
    private Queue<Integer>  queue2 = new LinkedBlockingQueue<>() ;
    
    
    public void push(int data){
        queue1.add(data);
    }
    
    public int pop() throws Exception{
        int data;
        if(queue1.size() == 0){
            throw new Exception("栈为空");
        }
        while(queue1.size() != 0){
            if(queue1.size() == 1){
                data = queue1.poll();
                while(queue2.size()!=0){
                    queue1.add(queue2.poll());
                }
                return data;
            }
            queue2.add(queue1.poll());
        }
        throw new Exception("栈为空");
    }
    
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub
         Myqueue qu = new Myqueue();
         qu.push(1);
         qu.push(2);
         qu.push(3);
         int data = qu.pop();
         int data1 =qu.pop();
         int data2 =qu.pop();
         System.out.println(data);
         System.out.println(data1);
         System.out.println(data2);
         
    }
}
复制代码

程序的运行结果是:

3

2

1

 

import java.util.Queue;import java.util.concurrent.ArrayBlockingQueue;import java.util.concurrent.LinkedBlockingQueue;
public class Myqueue {
private Queue<Integer>  queue1 = new LinkedBlockingQueue<>() ;private Queue<Integer>  queue2 = new LinkedBlockingQueue<>() ;public void push(int data){queue1.add(data);}public int pop() throws Exception{int data;if(queue1.size() == 0){throw new Exception("栈为空");}while(queue1.size() != 0){if(queue1.size() == 1){data = queue1.poll();while(queue2.size()!=0){queue1.add(queue2.poll());}return data;}queue2.add(queue1.poll());}throw new Exception("栈为空");}public static void main(String[] args) throws Exception {// TODO Auto-generated method stub         Myqueue qu = new Myqueue();         qu.push(1);         qu.push(2);         qu.push(3);         int data = qu.pop();         int data1 =qu.pop();         int data2 =qu.pop();         System.out.println(data);         System.out.println(data1);         System.out.println(data2);         }}

 

posted on   luzhouxiaoshuai  阅读(170)  评论(0编辑  收藏  举报

编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示