数据结构与算法02 -- 队列,数组实现队列,环形队列

队列

队列是一个有序列表,可以用数组或是链表来实现

先进先出

队列的输出、输入是分别从前后端来处理,因此需要两个变量 front 以及 rear 记录队列前后端的下标,front 会随着数据输出而改变,而 rear 则是随着数据输入而改变。

maxSize记录该队列的最大容量


数据存入队列

addQueue

  1. 当 front == rear 时,即队列为空,将尾指针往后移

  2. 若尾指针 rear 小于队列的最大下标 maxSize-1,则将数据存入 rear 所指的数组元素中,否则无法存入数据。

    rear == maxSize - 1 队列满


数组模拟队列

package queue;

import java.util.Scanner;

// array --> queue
public class Demo00 {
    public static void main(String[] args) {
        // test
        // create an queue
        ArrayQueue queue = new ArrayQueue(3);
        char key = ' '; // 接受用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        // 输出一个菜单
        while(loop){
            System.out.println("s(show):show the queue");
            System.out.println("e(exit):exit the app");
            System.out.println("a(add):add data to the queue");
            System.out.println("g(get):get data from the queue");
            System.out.println("h(head):look head data");
            key = scanner.next().charAt(0); // 接受一个字符
            switch (key){
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("please input a num");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g': // 取出数据
                   try{
                       int res = queue.getQueue();
                       System.out.printf("data is %d\n",res);
                   }catch (Exception e){
                        // handle exception
                       System.out.println(e.getMessage());
                   }
                   break;
                case 'h':
                     try{
                         int res = queue.headQueue();
                         System.out.printf("head is %d\n",res);
                     }catch (Exception e){
                         System.out.println(e.getMessage());
                     }
                     break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("app exit");
    }
}

// use array mimic queue -- write an ArrayQueue class
class ArrayQueue{
    private int maxSize;
    private int front; // point to queue head
    private int rear; // point to queue tail
    private int[] arr; // mimic queue

    // create queue's constructor
    public ArrayQueue(int arrMaxSize){
        maxSize = arrMaxSize;
        arr = new int[maxSize];
        front = -1; // 指向队列头的前一个位置
        rear = -1; // 指向队列尾的数据(即就是队列最后一个数据)
    }
    // 判断队列是否满
    public boolean isFull(){
        return rear == maxSize - 1;
    }
    // 判断队列是否为空
    public boolean isEmpty(){
        return rear == front;
    }
    // 添加数据到队列
    public void addQueue(int n){
        // 判断队列是否满
        if(isFull()){
            System.out.println("full");
            return;
        }
        rear++; // 让 rear 后移
        arr[rear] = n;
    }
    // 获取队列的数据,出队列
    public int getQueue(){
        // 判断队列是否空
        if(isEmpty()){
            // 通过抛出异常处理
            throw new RuntimeException("empty");
        }
        front++; // front 后移
        return arr[front];
    }
    // 显示队列所有数据
    public void showQueue(){
        // 遍历
        if(isEmpty()){
            System.out.println("empty queue");
        }
        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("empty");
        }
        return arr[front+1]; // 因为front指向的是头的前一个数据
    }
}

问题:目前数组使用一次就不能复用,没有充分的利用数组空间

改进:使用算法将数组改为环形队列 – 取模


数组模拟环形队列

  1. front 变量含义调整:front 就指向队列的第一个元素,也就是说 arr[front] 就是队列的第一个元素, front 初始值 = 0;
  2. rear 变量含义调整:rear 指向队列的最后一个元素的后一个位置,希望空出一个空间作为约定,rear 初始值 = 0;
  3. 当队列满时,条件是 [rear + 1] % maxSize == front
  4. 当队列为空的条件,rear == front
  5. 队列中有效的数据的个数:[rear + maxSize - front] % maxSize
package queue;

import java.util.Scanner;

// circle -- queue
public class Demo01 {
    public static void main(String[] args) {
        System.out.println("arr--circle queue");
        circleQueue queue = new circleQueue(4); // 队列的有效数据最大是3
        char key = ' '; // 接受用户输入
        Scanner scanner = new Scanner(System.in);
        boolean loop = true;
        // 输出一个菜单
        while(loop){
            System.out.println("s(show):show the queue");
            System.out.println("e(exit):exit the app");
            System.out.println("a(add):add data to the queue");
            System.out.println("g(get):get data from the queue");
            System.out.println("h(head):look head data");
            key = scanner.next().charAt(0); // 接受一个字符
            switch (key){
                case 's':
                    queue.showQueue();
                    break;
                case 'a':
                    System.out.println("please input a num");
                    int value = scanner.nextInt();
                    queue.addQueue(value);
                    break;
                case 'g': // 取出数据
                    try{
                        int res = queue.getQueue();
                        System.out.printf("data is %d\n",res);
                    }catch (Exception e){
                        // handle exception
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'h':
                    try{
                        int res = queue.headQueue();
                        System.out.printf("head is %d\n",res);
                    }catch (Exception e){
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'e':
                    scanner.close();
                    loop = false;
                    break;
                default:
                    break;
            }
        }
        System.out.println("app exit");
    }

}
class circleQueue{
    private int maxSize;
    private int front; // point to queue head
    private int rear; // point to queue tail
    private int[] arr; // mimic queue

    // create queue's constructor
    public circleQueue(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("full");
            return;
        }
        arr[rear] = n;
        // 将 rear 后移,必须考虑取模
        rear = (rear+1) % (maxSize);

    }
    // 获取队列的数据,出队列
    public int getQueue(){
        // 判断队列是否空
        if(isEmpty()){
            // 通过抛出异常处理
            throw new RuntimeException("empty");
        }
        // front 指向的是队列的第一个元素
        // 1 先把 front 对应的值保存在临时变量中
        // 2 把 front 后移
        // 3 将临时保存的变量返回
        int value = arr[front];
        front = (front+1) % maxSize; // front 后移
        return value;
    }
    // 显示队列所有数据
    public void showQueue(){
        // 遍历
        if(isEmpty()){
            System.out.println("empty queue");
        }
        // 从 front 开始遍历
        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("empty");
        }
        return arr[front]; // 因为front指向的是头的前一个数据
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值