I am displaying the contents of my implementation of a queue in Java. While the wrap around works (the size of the queue is 3), I'm having trouble displaying the queue when the front of the queue is greater than the rear.
Here is the code I'm using to display:
System.out.println("front");
System.out.println("=====");
if(front < rear ) {
for(int i = front; i != rear; 开发者_StackOverflow中文版i++ ) {
System.out.println(i +":> " + queue[i]);
}
}
else {
for(int i = front; i != rear; i= (i + 1) % SIZE ) {
System.out.println(i +":> " + queue[i]);
}
}
System.out.println("=====");
For example, let's say that front is 1, rear is 0 and SIZE = 3
.
My code prints out the contents of queue[1]
, queue[2]
in that order.
Why does it terminate when i == 2
? Shouldn't i= (i + 1) % SIZE
change the value of i
to 0 and thus make it equal to rear and then print out the value of queue[0]
?
When i == rear, your loop won't execute, because the i != rear is false. If you want to loop around, do something like:
int i = front;
do{
System.out.println(i +":> " + queue[i]);
i=(i+1)%Size;
}while(i != front)
Unless this is homework, why not use http://download.oracle.com/javase/6/docs/api/java/util/Queue.html ?
when i==2, it will become 0 at the end of the current iteration.
Then i==0, rear==0, i==rear, the loop terminates.
EDIT: This works but it doesn't look elegant
int i = front;
for(; i != rear; i= (i + 1) % SIZE ) {
System.out.println(i +":> " + queue[i]);
}
System.out.println(i +":> " + queue[i]);
Supposing SIZE = 3
and rear <= front
, so let's say rear = 0
, front = 2
, then the execution of your for loop does something like:
- Set
i = 2
- Execute body
- Set
i = (2+1) % 3 = 0
- Check
i != rear
, or0 != 0
, this is false, terminate loop.
Assuming this is a circular buffer, I'd iterate it like this:
int i = front;
do{
System.out.println(i);
i++;
if(i >= SIZE){
i = 0;
}
}while(i != (rear+1) % SIZE);
精彩评论