队列(Java实现)

队列

队列是一种先进先出的数据结构,First In First Out(FIFO)。

队列只能从队尾添加元素,同时也只能从队头取出元素。

1. 使用数组模拟队列

1.1 思路分析

  1. front初始值为-1,指向队列头的前一个位置
  2. rear初始值为-1,指向队列的最后一个元素
  3. 入队,往队尾添加元素,在添加前判断队列是否已满,尾指针自增
  4. 出队,从队头取出元素,在取出前判断队列是否为空,头指针自增

1.2 代码实现

public class ArrayQueue {
    public static void main(String[] args) {
        ArrQueue arrQueue = new ArrQueue(3);
        char key = ' ';  //接收用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop){
            System.out.println("s(show):显示队列");
            System.out.println("a(add):添加数据到队列");
            System.out.println("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头的数据");
            System.out.println("e(exit):退出程序");
            key = scanner.next().charAt(0);   //接收一个字符
            switch (key){
                case 's':
                    arrQueue.showQueue();break;
                case 'a':
                    System.out.println("输出一个数");
                    int value = scanner.nextInt();
                    arrQueue.addQueue(value);break;
                case 'g':
                    try {
                        int res = arrQueue.getQueue();
                        System.out.println("取出的数据是"+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = arrQueue.getHead();
                        System.out.println("队列头的数据是"+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:break;
            }
        }
        System.out.println("程序退出");
    }
}

class ArrQueue{        //创建一个用数组实现的队列
    private int maxSize;    //表示数组的最大容量
    private int front;      //队列头,front指向队列头的前一个位置
    private int rear;      //队列尾
    private int[] arr;     //用于存放数据,模拟队列

    public ArrQueue(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
        front = rear = -1;
    }
    public boolean isFull(){           //判断队列是否已满
        return rear == maxSize - 1;
    }
    public boolean isEmpty(){         //判断队列是否为空
        return rear == front;
    }
    public void addQueue(int n){   //入队
        if (isFull()){       //首先判断队列是否已满
            System.out.println("队列已满");
            return;
        }
        rear++;             //再尾指针后移
        arr[rear] = n;      //最后将数据插入到队尾
    }
    public int getQueue(){     //出队
        if (isEmpty()){        //首先判断队列是否为空
            throw new RuntimeException("队列为空");
        }
        front++;             //再头指针后移
        return arr[front];   //返回头指针指向的元素
    }
    public int getHead(){     //取队头元素
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return arr[front + 1];
    }
    public void showQueue(){   //打印队列
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println("arr["+i+"] = "+arr[i]);
        }
    }
}

2. 使用数组模拟环形队列

2.1 思路分析

  1. front初始值为0,指向队列的第一个元素
  2. rear初始值为0,指向队列的最后一个元素的后一个位置,因为要空出一个元素作为约定。
  3. 判断队满:(rear + 1)%maxSize == front
  4. 判断队空:rear == front
  5. 队列有效数据个数:(rear - front + maxSize)%maxSize

2.2 代码实现

public class CircleArrayQueue {
    public static void main(String[] args) {
        CircleArray circleArray = new CircleArray(4);   //创建一个环形队列,其队列的有效数据最大是3
        char key = ' ';  //接收用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        while (loop){
            System.out.println("s(show):显示队列");
            System.out.println("a(add):添加数据到队列");
            System.out.println("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头的数据");
            System.out.println("e(exit):退出程序");
            key = scanner.next().charAt(0);   //接收一个字符
            switch (key){
                case 's':
                    circleArray.showQueue();
                    break;
                case 'a':
                    System.out.println("输出一个数");
                    int value = scanner.nextInt();
                    circleArray.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = circleArray.getQueue();
                        System.out.println("取出的数据是"+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try {
                        int res = circleArray.getHead();
                        System.out.println("队列头的数据是"+res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:break;
            }
        }
        System.out.println("程序退出");
    }
}

class CircleArray{
    private int maxSize;    //表示数组的最大容量
    private int front;      //队列头,front指向队列的第一个元素
    private int rear;      //队列尾,rear指向队列的最后一个元素的后一个位置
    private int[] arr;     //用于存放数据,模拟队列

    public CircleArray(int maxSize) {
        this.maxSize = maxSize;
        arr = new int[maxSize];
    }
    public boolean isFull(){           //判断队列是否已满
        return (rear + 1)%maxSize == front;
    }
    public boolean isEmpty(){         //判断队列是否为空
        return rear == front;
    }
    public void addQueue(int n){   //入队
        if (isFull()){       //判断队列是否已满
            System.out.println("队列已满");
            return;
        }
        arr[rear] = n;
        rear = (rear + 1)%maxSize;   //需要考虑越界的问题
    }
    public int getQueue(){     //出队
        if (isEmpty()){        //判断队列是否为空
            throw new RuntimeException("队列为空");
        }
        int value = arr[front];
        front = (front + 1)%maxSize;
        return value;
    }
    public void showQueue(){   //打印队列
        if (isEmpty()){
            System.out.println("队列为空");
            return;
        }
        for (int i = front; i < front + getSize(); i++) {
            System.out.println("arr["+(i % maxSize)+"] = "+arr[i % maxSize]);
        }
    }
    public int getSize(){         //得到有效数据的个数
        return (rear - front + maxSize)%maxSize;
    }
    public int getHead(){    //取队头元素
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        return arr[front];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
延迟队列(DelayQueue)是 Java 并发包中提供的一种队列实现,用于存储具有延迟时间的元素。延迟队列中的元素只有在其指定的延迟时间过去后才能被取出。 下面是一个简单的延迟队列Java 实现示例: 首先,我们需要定义一个实现了 Delayed 接口的延迟元素类: ```java import java.util.concurrent.Delayed; import java.util.concurrent.TimeUnit; public class DelayedElement implements Delayed { private String data; private long startTime; public DelayedElement(String data, long delay) { this.data = data; this.startTime = System.currentTimeMillis() + delay; } @Override public long getDelay(TimeUnit unit) { long diff = startTime - System.currentTimeMillis(); return unit.convert(diff, TimeUnit.MILLISECONDS); } @Override public int compareTo(Delayed other) { if (this.startTime < ((DelayedElement) other).startTime) { return -1; } if (this.startTime > ((DelayedElement) other).startTime) { return 1; } return 0; } // Getter and Setter methods } ``` 然后,我们可以使用 DelayQueue 来存储延迟元素,并在需要时取出元素: ```java import java.util.concurrent.DelayQueue; public class DelayQueueExample { public static void main(String[] args) throws InterruptedException { DelayQueue<DelayedElement> delayQueue = new DelayQueue<>(); // 添加延迟元素到队列 delayQueue.add(new DelayedElement("Element 1", 2000)); // 延迟 2 秒 delayQueue.add(new DelayedElement("Element 2", 5000)); // 延迟 5 秒 delayQueue.add(new DelayedElement("Element 3", 1000)); // 延迟 1 秒 // 取出延迟元素并处理 while (!delayQueue.isEmpty()) { DelayedElement element = delayQueue.take(); System.out.println("Processing element: " + element.getData()); } } } ``` 在上面的示例中,我们创建了一个 DelayQueue 对象,并向其中添加了三个延迟元素。然后,我们使用 `take()` 方法从队列中取出元素,并进行处理。如果队列为空,`take()` 方法会阻塞等待,直到有延迟元素可用。 请注意,延迟时间的单位可以根据需要进行调整,例如使用 `TimeUnit.SECONDS` 表示秒。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值