嘿伙计们,我在尝试打印循环队列数组时遇到问题,这是我的代码:
public class CircularQueue {
private int [] queue;
private int front, rear;
// do not change the constructor
CircularQueue() {
queue = new int [5];
front = 0;
rear = -1;
}
// FILL IN:
// throws DSException if out of space
public void enqueue ( int item ) throws DSException {
if ( front == 0 && rear == -1 ){
throw new DSException();
}
queue[rear+1] = item;
rear = (rear+1)%queue.length;
}
// FILL IN:
// throws DSException if no element in the queue
// return the dequeued value
public int dequeue () throws DSException {
if ( front == 0 && rear == -1 ){
throw new DSException();
}
int temp = queue[front];
queue[front] = 0;
front = (front+1)%queue.length;
return temp;
}
// FILL IN:
// return the value at beginning of the queue
// throws DSException if no element in the queue
public int first () throws DSException {
return front;
}
// FILL IN:
// print the circular queue in the following format
// - print "+" before the value at the front
// - print "-" after the value at the rear
// - print "." for the places without valid element.
public void print () {
System.out.print(" <");
for ( int i = 0; i < queue.length; i++ ){
if ( front == 0 && rear == -1 ){
System.out.print("."+"\t");
} else if ( i == front ) {
System.out.print("+"+ queue[i]);
} else if ( i == rear ) {
System.out.print( queue[i]+ "-");
} else if ( i == front && i == rear) {
System.out.print("+"+ queue[i] +"-");
} else {
System.out.print( queue[i] );
}
}
System.out.print(">\n");
}
}
结果是 EMPTY: <. . . . . > 排队 (0):
我应该将 0-4 入队并将某些元素出队,但它在入队 0 后停止。