引言:
队列与栈的区别是队列是先进先出的数据结构。为了使得出入队列容易,可以引入队列头指针和队列尾指针。
分析描述:
队列的结点结构。
typedef int QElemType;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct{
QueuePtr front;//队列的头指针
QueuePtr rear;//队列的尾指针
}LinkQueue;
LinkQueue Q;
队列的初始化。
LinkQueue InitQueue(LinkQueue *Q)
{
QueuePtr tmp;
tmp = (QueuePtr)malloc(sizeof(QNode));
if(tmp == NULL){
printf("create queue error.\n");
return ;
}
Q->front = tmp;
Q->rear = Q->front;
Q->front->next = NULL;
return *Q;
}
入队列操作。
void EnQueue(LinkQueue *Q, QElemType e)
{
QueuePtr tmp;
tmp = (QueuePtr)malloc(sizeof(QNode));
if(tmp == NULL){
printf("create queue error.\n");
return ;
}
tmp->data = e;
tmp->next = NULL;
Q->rear->next = tmp;
Q->rear = tmp;
return;
}
出队列操作。
void DeQueue(LinkQueue *Q, QElemType *e)
{
QueuePtr tmp;
if(Q->front == Q->rear){
printf("the queue is empty.\n");
return ;
}
tmp = Q->front->next;
*e = tmp->data;
Q->front->next = tmp->next;
if(Q->rear == tmp)
Q->rear = Q->front;
free(tmp);
return;
}
取队列的头元素。
void GetHead(LinkQueue *Q, QElemType *e)
{
if(Q->front == Q->rear)
return;
*e = Q->front->next->data;
return ;
}
判断队列是否为空。
int QueueEmpty(LinkQueue *Q)
{
if(Q->front == Q->rear)
return TRUE;
return FALSE;
}
清空队列。
void ClearQueue(LinkQueue *Q)
{
if(Q->front == Q->rear){
printf("the queue is empty.\n");
return;
}
while(Q->front->next){
Q->rear = Q->front->next->next;
free(Q->front->next);
Q->front = Q->front->next;
}
Q->front->next = NULL;
Q->rear = Q->front;
return;
}
求队列的长度。
int QueueLength(LinkQueue Q)
{
int length = 0;
LinkQueue Tmp= Q;
while(Tmp.front != Tmp.rear){
length++;
Tmp.front = Tmp.front->next;
}
return length - 1;
}