数组模拟实现循环队列(JAVA)

队列:是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。

判空 front=rear;
判满 (rear+1)%Max_Size=front;
元素个数(rear-front+Max_Size)%Max_Size;

所能存放数据个数为数组的长度-1个

当存放满

class ArryQueue {
    
    
	private int Max_Size;//数组的长度
	private int front;//指向第一个元素
	private int rear;//指向最后一个元素的下一个位置,空出一个位置为约定
	private int[] arr;

	ArryQueue(int Size) {
    
    
		this.Max_Size = Size;
		arr = new int[Max_Size];
	}

	// 判空
	public boolean isEmpty() {
    
    

		return rear == front;
	}

	// 判满
	public boolean isFull() {
    
    
		return (rear + 1) % Max_Size == front;
	}

	// 入队
	public void EnterQueue(int n) {
    
    
		if (isFull())
			throw new RuntimeException("队列已满,不能插入元素");
		else
			arr[rear] = n;
		rear = (rear + 1) % Max_Size;
	}

	// 出队
	public int GetQueue() {
    
    
		if (isEmpty()) {
    
    
			throw new RuntimeException("当前队列为空");
		}
		int temp = arr[front];
		front = (front + 1) % Max_Size;
		return temp;
	}

	// 遍历队列中的所有元素
	public void showElement() {
    
    
		if (isEmpty()) {
    
    
			System.out.println("队列为空没有数据");
			return;
		}

		for (int i = front; i < front + size(); i++) {
    
    
			System.out.printf("arr[%d]=%d\n", i % Max_Size, arr[i % Max_Size]);
		}
	}
  //队列中所含元素个数
	private int size() {
    
    
		return (rear - front + Max_Size) % Max_Size;
	}
     //输出队头元素
	public int peek() {
    
    
		if (isEmpty()) {
    
    
			throw new RuntimeException("队列为空,没有数据");
		}
		return arr[front];
	}

猜你喜欢

转载自blog.csdn.net/qq_45630718/article/details/106324723