Analog data structure of the queue and white circular queue of

Brief queue:

* Queue is an ordered list, you can use an array or linked list to achieve
* FIFO queue follow the principle. Data stored in the first queue first removed, after extraction into

Using the array to simulate the queue

  1. Explanation
  2. Realization of ideas
  3. schematic diagram
  4. Code

1. Description

* Queue itself is an ordered list, by using an array of structures to store data queues, the queue is declared array is shown in the following figure, where the maximum capacity of the queue is maxSize

* Because the queue input and output respectively from the rear end to handle, it is necessary to front and rear two variables were recorded subscript front and rear ends of the queue, with the front output data is changed (moved upward), with the rear of the input data change (Move up)

2. realization of ideas

The data storage queue, the tail pointer is moved backward, rear + 1, the data output time, front + 1 output data, when the front == rear (empty queue).

If the tail pointer of the queue is less than the maximum rear subscript maxSize-1, then the queue is stored in the array elements referred to rear, or the data can not be stored, rear == maxSize-1 (full queue).

3. schematic

Here Insert Picture Description

4. Code:

1. Establishment and class constructor

class ArrayQueue {
    private int maxSize;//数组的最大容量
    private int front;  //指向队列头指针
    private int rear;   //指向队列尾指针
    private int[] arr;   //该数组用于存放数据

    //创建队列的构造器
    public ArrayQueue(int arrMaxSize) {
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        front = -1;//指向队列头部,此时指向队列头的前一个位置
        rear = -1;//指向队列的尾部,此时指向队列的最后一个位置
    }

2. determines whether the queue is empty or a full

//判断队列是否满
public boolean isFull() {
    return rear == maxSize - 1;
}

//判断队列是否为空
public boolean isEmpty() {
    return rear == front;
}

3. queues

//添加数据
public void addQueue(int n) {
    //判断队列是否满
    if (isFull()) {
        System.out.println("队列已满,不能加入数据");
        return;
    }
    rear++;//加入数据 尾指针后移
    arr[rear] = n;
}

4. dequeue

//出队列(获取队列数据)
public int getQueue() {
    if (isEmpty()) {
        throw new RuntimeException("队列已空,不能取出数据");
    }
    front++;

    return arr[front];
}

The display of the queue and the queue header data

//显示队列
public void showQueue() {
    if (isEmpty()) {
        System.out.println("队列为空,没有数据");
        return;
    }
    //printf用来进行输入各种占位符
    for(int i=0;i<arr.length;i++){
        System.out.printf("arr[%d]=%d\n",i,arr[i]);
    }
}

//显示队列的头数据
public int headQueue() {
    if (isEmpty()) {
        throw new RuntimeException("队列为空");
    }
    return arr[front + 1];
}

6. The main function test

public static void main(String[] args) {
    //创建一个队列
    ArrayQueue arrayQueue = new ArrayQueue(3);
    char key = ' ';//接收用户输入
    Scanner scanner = new Scanner(System.in);
    //输出
    boolean loop = true;
    while (loop) {
        System.out.println("s(show):显示队列");
        System.out.println("e(exit):退出队列");
        System.out.println("a(add):添加队列到队列");
        System.out.println("g(get):从队列取出数据");
        System.out.println("h(head):查看队列头的数据");
        key = scanner.next().charAt(0);//接收一个字符
        switch (key) {
            case 's':
                arrayQueue.showQueue();
                break;
            case 'a':
                System.out.println("请输入一个数据:");
                int value=scanner.nextInt();
                arrayQueue.addQueue(value);
                break;
            case 'g':
                try {
                    int res=arrayQueue.getQueue();
                    System.out.printf("取出的数据是%d\n",res);
                }catch (Exception e){
                    System.out.println(e.getMessage());
                }
                break;

            case 'h':
               try {
                   int res=arrayQueue.headQueue();
                   System.out.printf("队列头的数据是%d\n",res);
               }catch (Exception e){
                   System.out.println(e.getMessage());
               }
                break;
            case 'e':
                scanner.close();
                loop=false;
                break;
        }
    }
    System.out.println("程序退出");
}

Note: the use of arrays to simulate a normal queue, used only once, it is necessary to improve the common queue is circular queue


Analog circular queue array

Ideas are as follows:
the meaning of 1.front variables to make an adjustment: front points to the first element of the array queue (original position before a pointer to the first element), that is to say arr [front] is the first element of the queue

A position after the last element pointing to the queue 2.rear (originally points to the last element) because you want an empty space in a convention

3. When the queue is full, the condition (rear + 1)% maxSize = front end to [] are coincident

4. The queue is empty, rear == front

0.rear initial value of the initial value of 0 5.front

6. The number of valid queue (rear + maxSize-front)% maxSize

have a test:
Here Insert Picture Description

Thus the code above may be modified as follows:

package com.lz.arrayqueue;

import java.util.Scanner;

/***
 * 环形数组实现队列的多次使用
 */
public class CircleArrayQueue {
//测试函数
    public static void main(String[] args) {
        //创建一个队列
        System.out.println("测试数组模拟环形队列的案例~");
        //最大有效数据为3(0--2)
        CircleArray arrayQueue = new CircleArray(4);
        char key = '  ';//接收用户输入
        Scanner scanner = new Scanner(System.in);
        //输出
        boolean loop = true;
        while (loop) {
            System.out.println("s(show):显示队列");
            System.out.println("e(exit):退出队列");
            System.out.println("a(add):添加队列到队列");
            System.out.println("g(get):从队列取出数据");
            System.out.println("h(head):查看队列头的数据");
            key = scanner.next().charAt(0);//接收一个字符
            switch (key) {
                case 's':
                    arrayQueue.showQueue();
                    break;
                case 'a':
                    System.out.println("请输入一个数据:");
                    int value = scanner.nextInt();
                    arrayQueue.addQueue(value);
                    break;
                case 'g':
                    try {
                        int res = arrayQueue.getQueue();
                        System.out.printf("取出的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;

                case 'h':
                    try {
                        int res = arrayQueue.headQueue();
                        System.out.printf("队列头的数据是%d\n", res);
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
            }
        }
        System.out.println("程序退出");
    }

}

//编写一个CircleArray的类
class CircleArray {
    private int maxSize;//数组的最大容量
    private int front;  //指向队列头指针 指向首部 初始值为0
    private int rear;   //指向队列尾指针 指向尾部后一个位置 初始值为0
    private int[] arr;   //该数组用于存放数据

    //创建队列的构造器
    public CircleArray(int arrMaxSize) {
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        front = 0;
        rear = 0;
    }

    //判断队列是否满
    public boolean isFull() {
        return (rear + 1) % maxSize == front;
    }

    //判断队列是否为空
    public boolean isEmpty() {
        return rear == front;
    }

    //添加数据
    public void addQueue(int n) {
        //判断队列是否满
        if (isFull()) {
            System.out.println("队列已满,不能加入数据");
            return;
        }
        arr[rear] = n;//因为rear已经指向了后一个位置
        rear = (rear + 1) % maxSize;//为了考虑前面的位置【循环使用】
    }

    //出队列(获取队列数据)
    public int getQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列已空,不能取出数据");
        }
        //front是指向队列的第一个元素
        //1.先把front对应的值保存到一个临时变量 然后将front后移
        int value = arr[front];
        front = (front + 1) % maxSize;
        return value;
    }

    //显示队列
    public void showQueue() {
        if (isEmpty()) {
            System.out.println("队列为空,没有数据");
            return;
        }
        //printf用来进行输入各种占位符
        //从front开始遍历 遍历多少个元素 当前有效元素:(rear+maxSize-front)%maxSize
        for (int i = front; i < front + size(); i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, arr[i % maxSize]);
        }
    }

    //求出当前队列的有效数据
    public int size() {
        return (rear + maxSize - front) % maxSize;
    }

    //显示队列的头数据
    public int headQueue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空");
        }
        return arr[front];
    }
}





He published 193 original articles · won praise 70 · views 120 000 +

Guess you like

Origin blog.csdn.net/Lzinner/article/details/94554733