数据结构与算法分析(Java语言描述)—— 队列

1. 队列的模型

      队列的基本惭怍是 enqueue(入队),他是在表的末端(叫作队尾(rear))插入一个元素,和 dequeue(出队),它是删除(并返回)在表的开头(也叫作队头(front))的元素。

2. 队列的数组实现

      如同栈的情况一样,对于队列而言任何的表的实现都是合法的。像栈一样,对于每一种操作,链表实现和数组实现都给出快速的 O(1) 的运行时间。

大部分情况下队列长度可以为固定值,不影响使用

public class Queue {

    private Object [] theArray;
    int currentSize;
    int front;
    int rear;

    Queue(int size){
        clear(size);
    }

    /**
     * 入队
     */
    public boolean enQueue(Object obj) throws Exception {
        if(currentSize >= theArray.length)
            throw new Exception("队列已满无法入队");
        theArray[rear++] = obj;
        currentSize++;
        return true;
    }

    /**
     * 出队
     */
    public Object deQueue() throws Exception {
        if(currentSize == 0)
            throw new Exception("队列为空");
        Object obj = theArray[front++];
        currentSize--;
        return obj;
    }
    public boolean isEmpty(){
        return currentSize==0;
    }

    /**
     * 查看队头元素
     */
    public Object peek(){

    }
    public void clear(int size){
        theArray = new Object[size];
        currentSize = 0;
        front = 0;
        rear = 0;
    }
}

3. 循环队列的数组实现

这里写图片描述

public class QueueArray {
    private Object [] theArray;
    private int front;
    private int rear;

    QueueArray(int maxSize){
        theArray = new Object[maxSize];
        front = rear = 0;
    }

    public boolean enQueue(Object obj){
        if( (rear + 1) % theArray.length == front){
            System.out.println("队列已满");
            return false;
        }
        theArray[rear] = obj;
        rear = rear % theArray.length + 1;
        return true;
    }

    public Object deQueue(){
        if( rear % theArray.length == front){
            System.out.println("队列为空");
            return false;
        }
        Object obj = theArray[front];
        front = front % theArray.length +1;
        return obj;
    }
    public boolean isEmpty(){
        return front == rear;
    }
}

猜你喜欢

转载自blog.csdn.net/baidu_37181928/article/details/80791714