16. Java implements circular queue

Java implements circular queue

  1. The array elem stores the queue elements.

front and rear stand for head and tail respectively.

usedSize indicates the number of significant bits stored.

allSize represents the length of the array.

The array only stores allSize - 1 element, and one more space is wasted.

The circular queue cannot use rear = rear + 1 to point to the next element, it will go out of bounds, but use this.rear = (this.rear+1) % this.allSize.



class QueueLink{
	int element [];
	int front;//to the head
	int rear;//to the tail
	int usedSize;//Number of significant digits.
	int allSize = 10;

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

2. The basic operation of circular queue.

a . Determine whether the queue is full.

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

b. Enqueue.

public void push(int val){
	// Determine if it is full.
	if(isFull()){
	    return;
	}
	this.elem[this.rear] = val;
	this.rear = (this.rear+1) % this.allSize;
	this.usedSize++;
}

c. Determine if the queue is empty.

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

d. Dequeue.

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

e. Get the head element.

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

f. Output queue element.

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();
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326398564&siteId=291194637