16 . java 实现循环队列

java 实现循环队列

  1 . 数组 elem 存储队列元素。

front 和 rear 分别表示对头和对尾。

usedSize表示存储的有效位的个数。

allSize表示数组的长度。

数组仅存储 allSize - 1 个元素,还有一个空间被浪费。

循环队列不能用rear = rear + 1指向下一个元素,会发生越界,而要用this.rear = (this.rear+1) % this.allSize。



class QueueLink{
	int elem[];
	int front;//对头
	int rear;//对尾
	int usedSize;//有效数字个数。
	int allSize = 10;

	public QueueLink(){
		this(10);
	}
	public QueueLink(int size){
		this.elem  = new int[size];
		this.front = 0;
		this.rear = 0; 
	}

2 . 循环队列的基本操作。

a . 判断队列是否为满。

public boolean isFull(){
	return (this.rear+1) % this.allSize == this.front;
}

b . 入队。

public void push(int val){
	//判断是否为满。
	if(isFull()){
	    return;
	}
	this.elem[this.rear] = val;
	this.rear = (this.rear+1) % this.allSize;
	this.usedSize++;
}

c . 判断队列是否为空。

public boolean isEmpty(){
	return this.front  == this.rear;
}

d . 出队。

public void pop(){
	if(isEmpty()){
		return;
	}
	this.elem[this.front] = -1;
	this.front = (this.front+1)%this.allSize;
	this.usedSize--;
}

e . 得到队头元素。

public int getTop(){
	if(isEmpty()){
		return -1;
	}
	return this.elem[this.front];
}

f . 输出队列元素。

public void show(){
	for(int i = this.front; i < this.rear; i = (i+1) % this.allSize){
		System.out.print(this.elem[i]+" ");
	}
	System.out.println();
}

猜你喜欢

转载自blog.csdn.net/alyson_jm/article/details/80242993