【数据结构与算法 | 基础篇】环形数组模拟队列

1. 前言

上文我们用环形单向链表实现了队列.接下来我们用环形数组来模拟队列.并实现了isFull(),isEmpty()等方法.

2. 环形数组模拟队列

(1). Queue接口 :

java 复制代码
public interface Queue<E> {
    //向队伍插入值, 插入成功返回true, 否则返回false
    boolean offer(E value);
    //对队头获取值, 但不移除
    E poll();
    //从队头获取值, 并移除队头
    E peek();
    //判断队伍是否为空
    boolean isEmpty();
    //判断队列是否已满
    boolean isFull();
}

(2). 环形数组模拟队列

java 复制代码
public class ArrayQueue<E> implements Queue<E>, Iterable<E>{
    //数组的容量
    private int capacity;
    //环形数组
    private E[] queue;
    //队头
    private int head = 0;
    //队尾
    private int tail = 0;
    public ArrayQueue() {
        capacity = 10;
    }

    public ArrayQueue(int capacity) {
        this.capacity = capacity;
        //数组capacity个位置存储数据, 剩下一个位置用来区分队伍是满了还是空了的情况
        queue = (E[]) new Object[capacity + 1];
    }

    @Override
    public boolean offer(E value) {
        //如果队伍已经满了, 那么添加元素失败
        if(isFull()) {
        return false;
    }
    queue[tail] = value;
    tail = (tail + 1) % queue.length;
        return true;
}

    @Override
    public E poll() {
        //如果队列为空, 那么返回null
        if(isEmpty()) {
            return null;
        }
        return queue[head];
    }

    @Override
    public E peek() {
        //如果队列为空, 那么返回null
        E value = queue[head];
        head = (head + 1) % queue.length;
        return value;
    }

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

    @Override
    public boolean isFull() {
        //数组的长度queue.length并不等于数组的容量capacity
        return (tail+1) % queue.length == head;
    }

    @Override
    public Iterator<E> iterator() {
        return new Iterator<E>() {
            int p = head;
            @Override
            public boolean hasNext() {
                return p != tail;
            }

            @Override
            public E next() {
                E value = queue[p];
                p++;
                return value;
            }
        };
    }
}

3. 单元测试

java 复制代码
public class ArrayQueueTest {
    @Test
    public void test() {
        ArrayQueue<Integer> queue = new ArrayQueue<>(5);
        queue.offer(1);
        queue.offer(2);
        queue.offer(3);
        queue.offer(4);
        queue.offer(5);
//        for (Integer element : queue) {
//            System.out.print(element);
//        }
        //12345
        System.out.println(queue.poll());
        //1
        System.out.println(queue.peek());
        //1
        System.out.println(queue.poll());
        //2
    }
}
相关推荐
怀旧,2 小时前
【数据结构】8. 二叉树
c语言·数据结构·算法
凤年徐3 小时前
【数据结构与算法】203.移除链表元素(LeetCode)图文详解
c语言·开发语言·数据结构·算法·leetcode·链表·刷题
浩瀚星辰20245 小时前
C++树状数组详解
java·数据结构·算法
起个数先5 小时前
快速排序算法(Java)
数据结构·排序算法
chao_78913 小时前
二分查找篇——搜索旋转排序数组【LeetCode】两次二分查找
开发语言·数据结构·python·算法·leetcode
秋说15 小时前
【PTA数据结构 | C语言版】一元多项式求导
c语言·数据结构·算法
谭林杰16 小时前
B树和B+树
数据结构·b树
卡卡卡卡罗特17 小时前
每日mysql
数据结构·算法
chao_78918 小时前
二分查找篇——搜索旋转排序数组【LeetCode】一次二分查找
数据结构·python·算法·leetcode·二分查找