Data structure and algorithm_array simulation circular queue

1. What is a circular queue?
Answer: The circular queue is first and foremost a linear data structure, that is, an ordered list. Second, it follows the first-in first-out principle, namely FIFO (first in first out). The circular queue is a more efficient data structure designed to make up for the problem of false overflow of ordinary queues.
Insert picture description here
2. How to use an array to simulate a circular queue?
answer:

  • The output and input of the queue are processed separately from the front and back ends. Therefore, two variables front and rear are required to record the subscripts of the front and back ends of the queue. Front will change with the data output, and rear will change with the data input.
  • Definition maxSize is the maximum capacity of the queue.
  • It is clear how to judge when the queue is empty: when rear == front, this judgment condition does not change whether it is a normal queue or a circular queue.
  • How to determine when the queue is full: when (rear + 1)% maxSize == front full]
  • Initially, the initial values ​​of rear and front are both 0. (For ordinary queues, the initial value is -1)
  • How to insert an element: First of all, you have to judge whether the queue is empty, then insert the element directly to the position where the rear is located, and set the rear + 1, but pay attention to use% to take the remainder of the maximum capacity.
 public void addQueue(int n) {
   if (isFull()) {
	System.out.println("队列满,无法加入..");
	return;}
	arr[rear] = n;
	rear = (rear + 1) % maxSize;}  
  • How to pop up elements:
public int getQueue() {
  	if (isEmpty()) {
		throw new RuntimeException("队列空~");}
		int value = arr[front];
		front = (front + 1) % maxSize;
		return value;}

3. Knowledge points learned

  • How to write the initialization function of the class
 def __init__(self,size=3):
 #这里size如果没有写参数时,则默认初始化为3
        self._size = size+1   #java代码中的maxSize
        self._data = [0]*(size+1) #带self的变量都是类的属性
        self._front = 0
        self._rear = 0
  • When the circular queue is initialized to create an empty team, let front = rear = 0;
    when the team is empty: front = rear
    When the team is full: front = rear is also established,
    so it is necessary to agree when the queue head pointer is at the next position of the queue pointer rear As a sign of "full" status.
    which is:

When the team is full: (rear + 1)% maxsize = front

Complete code:

package com.xiaofan.Arrayqueue;

import java.util.Scanner;

public class CircleArrayQueue {

	public static void main(String[] args) {
		// 测试
		System.out.println("测试循环数组");
		ArrayQueue arr = 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':arr.show();break;
			case 'e':
				scanner.close();
				loop = false;
				break;
			case 'a':
				System.out.println("输入一个数:");
				int value = scanner.nextInt();
				arr.addQueue(value);
				break;
			case 'g':
				try {
					//System.out.println("df");
					int res = arr.getQueue();
					System.out.printf("取出数据为%d",res);
				}catch(Exception e) {
					e.getMessage();
				}
				break;
			case 'h':
				try {
					int res = arr.headQueue();
					System.out.printf("队列的头数据为%d\n",res);
				}catch(Exception e) {
					e.getMessage();
				}
				break;
			default:
				break;
				
			}
		}
		System.out.println("程序退出!");

	}

}

class CirleArray{
	private int maxSize;// 表示最大容量
	private int front;//初始时指向0
	private int rear;//初始时指向0
	private int[] arr;
	
	public CirleArray(int arrMaxSize) {
		maxSize = arrMaxSize;
		arr = new int [maxSize];
	}
	
	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 + 1) % maxSize;
	}
	
	public int getQueue() {
		
		if (isEmpty()) {
			// 抛异常
			System.out.println("队列为空");
			throw new RuntimeException("队列为空,不能取值\n");
		}
		//1.先临时保存队列头部的值
		//2.再将front后移,考慮取余
		//3。再把临时保存的值返回
		int value = arr[front];
		front = (front + 1) % maxSize;
		return value;
	}

	public void show() {
		//int p = front + 1;
		if (isEmpty()) {
			System.out.println("队列为空,无法显示");
		}
		//从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("队列为空,没有数据");
			}
			return arr[front];
		}

}
Published 27 original articles · praised 2 · visits 680

Guess you like

Origin blog.csdn.net/qq_44273739/article/details/104849730