Java data structure and algorithm (3): queue

Also a queue table, except that the queues at one end and inserted at the other end to delete.

Queuing model

Basic operation queue comprises enqueue, dequeue operations. At the end of the table element is inserted, deleted elements at the beginning of the table, i.e., first in first out (FIFO).

Array implementation of a queue

For each queue data structure, an array of items to retain, and Back and front positions, respectively, at both ends of the queue, but also record the number of elements in size. Operation should be: when a element x enqueue, size, and by a back, set items [back] = x; when dequeued return items [front], size minus 1, and by a front.

Initial queue:

Into the team:

The team:

Since the array is bounded, the process is repeated many times, is the last possible back an index of the array, and the array after several teams operating out of the remaining few might not have even the elements, solution is to only front or back end of the array of arrival, it has rewind to the beginning , this is called loop through the array to achieve.
Initial state:

After 1 into the team:

After twice into the team:

After coming out from the team:

After two times the teams:

After three from the team:

After four times from the team:

The sample code

On queue, and finally is enqueue dequeue operations, as used herein, the first team and the tail relationship with the length of the array is determined whether the queue is empty, it is full:

public class MyArrayQueue<T> {
    private int front;
    private int back;
    private T[] items;
    private static final int DEFAULT_CAPACITY = 10;

    public MyArrayQueue() {
        this(DEFAULT_CAPACITY);
    }

    public MyArrayQueue(int size) {
        front = back = 0;
        items = (T[]) new Object[size];
    }

    public boolean isEmpty() {
        return front == back;
    }

    public void enqueue(T x) throws Exception {
        if ((back + 1) % items.length == front) {
            throw new Exception("队列已满");
        }
        items[back] = x;
        back = back % items.length + 1;
    }

    public T dequeue() throws Exception {
        if (back % items.length == front) {
            throw new Exception("队列为空");
        }
        T x = items[front];
        front = front % items.length + 1;
        return x;
    }
}

Guess you like

Origin www.cnblogs.com/xiaoxiaoyihan/p/11611748.html