加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

普通数组-队列

发布时间:2020-12-15 07:54:44 所属栏目:Java 来源:网络整理
导读:package data.struct; import java.util.Arrays; public class ArrayQueue { private int maxSize; // 队列最大长度 private int head; // 队列头 private int tail; // 队列尾 private int [] array; public static void main(String[] args) { ArrayQueue
package data.struct;

import java.util.Arrays;

public class ArrayQueue {

    private int maxSize;//队列最大长度
    private int head;//队列头
    private int tail;//队列尾
    private int[] array;
    
    public static void main(String[] args) {
        ArrayQueue queue = new ArrayQueue(3);
        queue.showHead();//0
        queue.add(1);
        queue.showHead();//1
        queue.showQueue();//[1,0]
        queue.add(2);
        queue.showQueue();//[1,2,0]
        queue.add(3);
        queue.showQueue();//[1,3]
        System.out.println(queue.get());//1
        queue.showHead();//2
        System.out.println(queue.get());//2
        System.out.println(queue.get());//3
    }
    
    public ArrayQueue(int maxSize) {
        if(maxSize < 0) {
            throw new RuntimeException("invalid param");
        }
        this.maxSize = maxSize;
        array = new int[maxSize];
        head = 0;//队列首位置
        tail = -1;//队列位位置
    }
    
    public boolean isEmpty() {
        return tail < head;//tail == head,则代表队列恰好有一个元素
    }
    
    public boolean isFull() {
        return tail == maxSize - 1;
    }
    
    //出队列
    public int get() {
        if(isEmpty()) {
            throw new RuntimeException("array queue is empty");
        }
        head++;
        return array[head-1];
    }
    
    //入队列
    public void add(int num) {
        if(isFull()) {
            throw new RuntimeException("arrat queue is full");
        }
        tail++;
        array[tail] = num;
    }
    
    //打印队列头
    public void showHead() {
        System.out.println(array[head]);
    }
    
    //打印整个队列
    public void showQueue() {
        System.out.println(Arrays.toString(array));
    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读