特殊的线性表,插入在队尾,删除的是对头。

  先进先出。

 

一:队列

1.普通队列实现

package com.jun.algorithm.foundation.main;

/**
 * 使用数组实现队列
 *
 * @author caojun
 */
public class ArrayQueue {

    private int[] data;
    // 对头的位置
    private int head = 0;
    // 队尾的位置
    private int tail = 0;
    // 队列长度
    private int n = 0;

    ArrayQueue(int cap) {
        data = new int[cap];
        n = cap;
    }

    public void push(int num) {
        // 如果没有空间了,移动一次
        if (tail == n) {
            return;
        }
        data[tail] = num;
        tail++;
    }

    public int pop() {
        if (isEmpty()) {
            return -1;
        }
        int m = data[head];
        head++;
        return m;
    }

    public boolean isEmpty() {
        return head == tail;
    }


}

 

2.循环队列实现

package com.jun.algorithm.foundation.main;

/**
 * 使用数组实现循环队列
 *
 * @author caojun
 */
public class CircleArrayQueue {

    private int[] data;
    // 对头的位置
    private int head = 0;
    // 队尾的位置
    private int tail = 0;
    // 队列长度
    private int n = 0;

    CircleArrayQueue(int cap) {
        data = new int[cap];
        n = cap;
    }

    public void push(int num) {
        // 满了的判断条件
        if ((tail + 1) % n == head) {
            return;
        }
        data[tail] = num;
        tail = (tail + 1) % n;
    }

    public int pop() {
        if (isEmpty()) {
            return -1;
        }
        int m = data[head];
        head = (head + 1) % n;
        return m;
    }

    public boolean isEmpty() {
        return head == tail;
    }


}

 

 posted on 2022-03-16 23:01  曹军  阅读(44)  评论(0编辑  收藏  举报