InitQueue(&Q): 初始化队列Q
QueueEmpty(): 判断队列是否为空
EnQueue(e): 将元素e放入队尾
DeQueue(e): 移走队头元素,由e带回该元素的值
GetFront(): 获取队头元素的值,但不从队列中移走该元素
Length(): 计算并返回队列中元素的个数
#include <stdio.h>
#include <stdlib.h>
typedef struct QNode{
int data;
struct QNode *next;
}QNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
bool InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));
if(!Q.front)
return false;
Q.front->next = NULL;
return true;
}
bool QueueEmpty(LinkQueue &Q){
if(Q.front == Q.rear)
return true;
else
return false;
}
bool EnQueue(LinkQueue &Q,int e){
QueuePtr p;
p = (QueuePtr)malloc(sizeof(QNode));
if(!p)
return false;
p->data = e;
Q.rear->next = p;
Q.rear = p;
Q.rear->next = NULL;
return true;
}
int GetFront(LinkQueue &Q){
return Q.front->next->data;
}
int Length(LinkQueue &Q){
int count = 0;
QueuePtr p= Q.front;
while(p != Q.rear){
count++;
p = p->next;
}
return count;
}
int DeQueue(LinkQueue &Q){
QNode *p;
p = Q.front->next;
int e = p->data;
Q.front->next = p->next;
free(p);
return e;
}
int main(){
LinkQueue Q;int e;
InitQueue(Q);
if(QueueEmpty(Q))
printf("链队列为空!\n");
else
printf("链队列不为空!\n");
for(int i=0;i<5;i++){
printf("请输入第%d个数据:",1+i);
scanf("%d",&e);
EnQueue(Q,e);
}
if(QueueEmpty(Q))
printf("链队列为空!\n");
else
printf("链队列不为空!\n");
printf("队头元素:%d\n",GetFront(Q));
printf("元素个数:%d\n",Length(Q));
printf("已删除队头元素:%d\n",DeQueue(Q));
printf("队头元素:%d\n",GetFront(Q));
printf("元素个数:%d\n",Length(Q));
return 0;
}