Detailed explanation of data structure queue and code demonstration

queue

One of the common data structures, queue is a sequential list, which can be realized by array or linked list
Following the principle of first in first out, the dual end queue can be two in and two out. The current stack is implemented by using the dual end queue Deque

1.1 sequential queue

1.1.1 introduction to sequential queue

1. The rear pointer refers to the end of the queue, and the front pointer refers to the end of the queue, which will change with the data output and input
Each time an element is inserted at the end of the team, the rear is increased by 1;
Each time an element is deleted at the head of the queue, the front is incremented by 1.
Move the tail pointer back: rear+1, when front == rear (null).
2. If the tail pointer rear is less than the maximum subscript maxSize-1 of the queue, the data will be stored in the array element referred to by rear, otherwise the data cannot be stored. rear==maxSize-1 (queue full)
3. With the insertion and deletion operations, the number of queue elements changes constantly, and the storage space occupied by the queue also moves in the continuous space allocated for the queue structure.
4. When the rear increases beyond the allocated continuous space, the queue cannot insert new elements, but there is often a large amount of available space unoccupied. These spaces are the storage units once occupied by queue elements that have been out of the queue.

1.1.2 overflow in sequential queue:

(1) "Underflow" phenomenon: when the queue is empty, the overflow phenomenon caused by queue operation is made. "Underflow" is a normal phenomenon, which is often used as a condition for program control transfer.
(2) "True overflow" phenomenon: when the queue is full, the stack operation will cause space overflow. "True overflow" is an error state and should be avoided.
(3) "False overflow" phenomenon: the space of deleted elements can never be reused because the head and tail pointers only increase but not decrease in the queue entry and exit operations. When the actual number of elements in the queue is far less than the scale of the vector space, the queue operation may not be performed because the tail pointer has exceeded the upper bound of the vector space. This phenomenon is called "false overflow".

1.1.3 demonstration of using array code

public class QueueDemo {
    public static void main(String[] args) {
        //test
        //Create a queue
        ArrayQueue arrayQueue = new ArrayQueue(5);
        char key = ' ';//Accept user input
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            System.out.println("s(show):Show queue");
            System.out.println("e(exit):Exit program");
            System.out.println("a(add):Add data to queue");
            System.out.println("g(get):Fetch data from queue");
            System.out.println("h(head):View data of queue header");
            System.out.println("Please enter your options:");
            key = scanner.next().charAt(0);//Accept one character
            switch (key) {
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("Enter a number:");
                    int value = scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int result = arrayQueue.getQueue();
                        System.out.println("The extracted data are:" + result);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h'://View queue header information

                    try {
                        int result = arrayQueue.headQueue();
                        System.out.println("The data of the queue header is:" + result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'e':
                    scanner.close();
                    flag = false;
                default:
                    break;
            }
        }
        System.out.println("Program exit");
    }
}

//Use arrays to simulate queues - write an ArrayQueue class
class ArrayQueue {
    private int maxSize;//Represents the largest container for an array
    private int front;//Queue header
    private int rear;//Queue tail
    private int[] arr;//This data is used to store data and simulate the queue

    //Constructor to create a queue
    public ArrayQueue(int arrMaxSize) {
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        front = -1;//Point to the head of the queue. It is analyzed that front is the previous position pointing to the head of the queue
        rear = -1;//Data pointing to the end of the queue (that is, the last data of the queue)
    }

    //Is the queue full
    public boolean isFull() {
        return rear == maxSize - 1;
    }

    //Determine whether the queue is empty
    public boolean isEmpty() {
        return rear == front;
    }

    //Add data to queue
    public void addQueue(int n) {
        //Determine whether the queue is full
        if (isFull()) {
            System.out.println("The queue is full and data cannot be added");
            return;
        }
        rear++;//Move rear
        arr[rear] = n;
    }

    //Get the data of the queue and get out of the queue
    public int getQueue() {
        //Determine whether the queue is empty
        if (isEmpty()) {
            //By throwing an exception
            throw new RuntimeException("The queue is empty and data cannot be retrieved");
        }
        front++;//front backward
        return arr[front];
    }

    //Displays all data for the queue
    public void showQueue() {
        //ergodic
        if (isEmpty()) {
            System.out.println("The queue is empty and there is no data");
            return;
        }
        for (int i = 0; i < arr.length; i++) {
            System.out.println(i + "," + arr[i]);
        }
    }

    //The header data of the queue is displayed. Note that it is not taken out
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("The queue is empty and there is no data");
        }
        return arr[front + 1];
    }
}

1.1.4 result display

1.2 circular queue

1.2.1 introduction to circular queue

Cyclic queues can be reused
Using the algorithm, this array is improved into a ring queue module (%)

1.2.2 ideas

1. Adjust the meaning of the front variable: front points to the first element of the queue, that is, arr[front] is the first element of the queue
The initial value of front is 0
2. Make an adjustment to the meaning of the rear variable: the rear variable points to the next position of the last element of the queue, because you want to free up a space as a convention
The initial value of real is 0
3. When the queue is full, the condition is (rear+1)% maxsize = front (full) (loop)
4. When the queue is empty, rear==front is empty
5. When we analyze in this way, the number of valid data in the queue (rear + maxsize front)% maxsize
6. We can modify the original code to get the ring queue

1.2.3 demonstration of using array code

public class QueueDemo1 {
    public static void main(String[] args) {
        //Test, create a queue first
        CircleQueue arrQueue = new CircleQueue(5);
        char key = ' ';
        Scanner scanner = new Scanner(System.in);
        boolean flag = true;
        while (flag) {
            System.out.println("s(show): Show queue");
            System.out.println("a(add): Add data to queue");
            System.out.println("g(get):Fetch data from queue");
            System.out.println("h(head): View data of queue header");
            System.out.println("e(exit): Exit program");
            System.out.println("Please enter your options:");
            key = scanner.next().charAt(0);//Accept one character
            switch (key) {
                case 's':
                    arrQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("Please enter a number:");
                    int value = scanner.nextInt();
                    arrQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int result = arrQueue.getQueue();
                        System.out.println("The extracted data are:"+result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'h':
                    try {
                        int result = arrQueue.headQueue();
                        System.out.println("The data of the queue header is:"+result);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 'e':
                    scanner.close();
                    flag=false;
            }
        }
        System.out.println("Program exit!");
    }
}

/***
 *@Descriptin Use an array to simulate a queue and write an ArrayQueue class
 *@data 2021/12/3
 */
class CircleQueue {
    private int maxSize;//Represents the largest container for an array
    private int front;//Queue header, front initialized to 0
    private int rear;//At the end of the queue, the initial capacity of the rear is 0
    private int[] arr;//This array is used to store arrays and simulate queues

    //Create a queue
    public CircleQueue(int arrMaxSize) {
        maxSize = arrMaxSize;
        arr = new int[maxSize];
    }

    //Determine whether the queue is full
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    //Determine whether the queue is empty
    public boolean isEmpty() {
        return rear == front;
    }

    //Add data to queue
    public void addQueue(int number) {
        if (isFull()) {
            System.out.println("Queue full, unable to add data!");
            return;
        }
        arr[rear] = number;
        //Move the rear, and here you must consider taking the mold
        rear = (rear + 1) % maxSize;
    }

    //Get the data of the queue and get out of the queue
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("The queue is empty and data cannot be fetched");
        }
        /**
         * Here, we need to analyze that front is the first element pointing to the queue
         * 1.First, keep the value corresponding to front to a temporary variable
         * 2.Move the front back and consider taking the mold
         * 3.Variables to be temporarily saved
         */
        int value = arr[front];
        front = (front + 1) % maxSize;
        return value;
    }

    //Displays all data for the queue
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("Queue is empty, no data!");
            return;
        }
        for (int i = 0; i < front + size(); i++) {
            System.out.println(i % maxSize + ",arr[" + arr[i % maxSize] + "]");
        }
    }

    //Find the number of valid data in the current queue
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    //The header data of the queue is displayed. Note that it is not fetched
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("The queue is empty and there is no data!");
        }
        return arr[front + 1];
    }
}

1.2.4 result display

Tags: Algorithm data structure queue

Posted on Sun, 05 Dec 2021 04:28:50 -0500 by afatkidrunnin