Article Directory
Sequential storage structure
The so-called sequential storage structure is a set of consecutive addresses are sequentially stored from the storage unit to the tail queue head element.
Statement two pointers rear
, front
are used to indicate the next position and the position of the tail element of the head elements.
Initialization rear = front = 0
, when inserting a new element of the tail pointer is incremented, when the head-of-queue element pointer.
But there is a problem to do so, whether the team is still a team, team head or the tail pointer is incremented by one, to do so there is a problem, is the element of the team vacated space can not be re-utilized .
Although the actual number of elements in the queue memory is much smaller than the size of storage space, but the team still do the operation. This phenomenon is calledFalse overflow。
Circular queue
Circular queue is a queue of one implementation of the sequential storage structure . It is imagined by a queue order annular end to end, to overcome the problem of false overflow.
Circular queue can not pass through the same head and tail pointer to determine whether the state of the queue is empty or full, because in this case may be empty or may is full .
Circular queue space at least one element, the "head pointer at the next position of the tail pointer" as a determination flag of the queue is full through.
Code
#define MAXQSIZE 100 //队列最大长度
typedef struct{
int *base; //动态分配存储空间
int front; //头指针,若队列不空指向队首元素
int rear; //尾指针,指向队尾元素的下一位置
int queueSize;
} SqQueue;
bool initQueue(SqQueue &Q, int maxSize){
Q.base = new int[maxSize];
if(!Q.base){exit(-1);}
Q.queueSize = maxSize;
Q.front = Q.rear = 0;
return true;
}
bool enQueue(SqQueue &Q, int e){
if((Q.rear + 1) % Q.queueSize == Q.front){
return false;
}
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % Q.queueSize;
return true;
}
bool deQueue(SqQueue &Q, int &e){
if(Q.front == Q.rear){
return false;
}
e = Q.base[Q.front];
Q.front = (Q.front + 1) % Q.queueSize;
return true;
}
note
- If
rear = front
it can be determined queue is empty - If
(rear + 1) % size == front
, queue is full it can be determined (rear - front + size) % size
A queue length