C++/explanations about the code pls
Expert: vijayan - 11/27/2009
QuestionHi,
please, i seen this queue implementation in a textbook and i am abit confused about a statement in the code: "if(tail+1==head || (tail+1==SIZE && != head)".why add a 1 to the tail? could you explain with the aid of a circular queue diagram? i do know itz a circular queue.
void enqueue(int num){
/*the next statement is what i really dont understand*/
if(tail+1==head || (tail+1==SIZE && != head){
cout<<"queue is full!!!";
return;
}
/*check dat the queue is rotating*/
if(tail == SIZE) tail = 0;
queue[SIZE]= num;
}
Answer /*the next statement is what i really dont understand*/
if(tail+1==head || (tail+1==SIZE && != head){
This will not compile; it has a syntax error.
Perhaps it should have been
if( ( tail+1==head ) || ( (tail+1==SIZE) && (0==head) ) ){
This is a circular queue implemented using an array of size SIZE.
head is the index of the first element, tail is the index of the last element.
if you want to add a new element to the queue, its position would be tail+1.
The if statement
a. checks if this position is the position of the first element; if so the queue is full. ( tail+1==head )
b. if the current position of tail is the last element of the array (tail+1==SIZE)
i. the position of the new element would be 0 - circular, so go to the start of the array
ii. if the beginning of the array is occupied by the first element the queue is full (0==head)
For a diagram see
http://datastructures.itgo.com/staque/queues/circular/insert.htm
the 'front' is your 'head', the 'rear' is your 'tail'