Queue 队列用数组实现 只用一次的

Queue 可以用数组,也可以用链表来实现

我们会有两个指针,一个指针负责添加数据,一个指针负责减少数据

注意:font 用来取数据,所以第二次取,要娶下一个

package structure;

public class QueDemo {
    public static void main(String[] args) {

    }
}

class Que{
    private int maxSize;
    private int font;
    private int rear;
    private int [] arr ;

    public Que(int maxSize) {
        font =-1;//指向队列的前一个位置。
        rear = -1;//就是指向队列尾部
        arr = new int[maxSize];
        this.maxSize = maxSize;
    }


    public boolean isfull() {
        return rear == maxSize-1;
    }

    public boolean isEmpty() {
        return rear == font;//因为这个font 指向的就是已经取走了的数据的位置。所以,如果存储的位置已经被取走了。那么就是没有数据了。
    }

    public void add(int num) {
        if (isfull()) {
            System.out.println("已满");

        } else {
            rear++;
            arr[rear] = num;//添加的时候就是指哪添加到哪。所以是一致的。
        }

    }

    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("为空");
        }else {
            font++;
            return arr[font];//因为font指向的数据被取走了。所以必须是下一个
        }
    }

    public void show() {
        if (isEmpty()) {
            System.out.println("没数,怎么打印?");
            return;
        }else {
            for (int i = 0; i < arr.length; i++) {
                int i1 = arr[i];
                System.out.println("i1 = " + i1);
            }
        }



    }

    public int peek(){
        if (isEmpty()) {
            throw new RuntimeException("没有,怎么偷看?");
        } else {
            return arr[font];
        }
    }
}

queue最重要的一共就是三个参数,存用一个指针,取用一个指针记录,然后就是maxsize最大的存储上线。也就是个数。
因为这个指针是数组的下标。所以是从 第一个肯定是 0 。

以上的方法中,重要的一个 isfull 主要是 为了 add方法用的
isempty 是为了get 方法用的。 打印是必须有的。

以上方法中最难理解的在于isEmpty方法的理解。一定要用自己的理解方式来理解代码。要么无法记住。


以上的队列,只能使用一次

发布了66 篇原创文章 · 获赞 0 · 访问量 793

猜你喜欢

转载自blog.csdn.net/Be_With_I/article/details/103981519