队列 +java +数据结构

队列

特殊线性表,只允许在 front 表的前端进行 删除操作, 在表的后端rear进行插入操作。

就是所谓的 先进先出。

在这里插入图片描述

分为 顺序队列 和 循环队列

顺序队列

一个连续空间
两个指针管理: 一个头指针,一个尾指针。
在这里插入图片描述

假溢出和真溢出

假溢出
在这里插入图片描述

真溢出
在这里插入图片描述

关注点:
添加元素的时候,front指针。
删除元素的时候,rear指针。

判断什么时候是空队列:

代码

package queue;

public class ArrayQueue {
    private int[] array;
    private int maxSize;
    private int frontPoint;
    private int rearPoint;


    public ArrayQueue(int maxSize){
        this.maxSize = maxSize;
        array = new int[maxSize];

        frontPoint = -1;
        rearPoint = -1;
    }

    // whether the current queue is full
    // 判断当前队列 是否 满了
    public boolean isFull(){
        return rearPoint == maxSize - 1;
    }

    // whether the current queue is empty
    // 判断当前队列 是否 空
    public boolean isEmpty(){
        return rearPoint == frontPoint;
    }

    // add element into queue
    // 添加元素
    public void add(int n){
        if (isFull()){
            System.out.println("the queue is already full!");
            return;
        }
        rearPoint++;
        array[rearPoint] = n;

    }

    // delete element from queue
    // 获取元素
    public int get(){
        if (isEmpty()){
            throw new RuntimeException("Empty queue!");
        }

        frontPoint ++;
        return array[frontPoint];
    }

     // showing each element in queue
    // 查看队列中的元素
    public void findQueue(){
        if (isEmpty()){
            throw new RuntimeException("Empty queue!");
        }

        int index = 0;
        for(int i = frontPoint + 1; i < array.length; i++){
            System.out.printf("array[%d] = %d\n",index,array[i]);
            index += 1;
        }
    }

    // showing the first front element
    public int frontQueue(){
        if (isEmpty()){
            throw new RuntimeException("Empty queue!");
        }
        return array[frontPoint + 1];
    }
}

测试

package queue;

public class TestApp {
  public static void main(String[] args) {
    //
      // 创建队列
      ArrayQueue arrayQueue = new ArrayQueue(5);
      
      // 添加元素
      arrayQueue.add(1);
      arrayQueue.add(2);
      arrayQueue.add(3);
      arrayQueue.add(4);
      arrayQueue.add(5);
//      arrayQueue.findQueue();
      
      // 取出第一个元素
      arrayQueue.get();
      arrayQueue.get();
      
      // 查看队列内的元素
      arrayQueue.findQueue();
      
      // 查看队列第一个元素
      System.out.println(arrayQueue.frontQueue());
  }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值