链式队列的C语言实现,数据元素为字符串。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define ERROR 0
#define OK 1
typedef int Status;
typedef struct QNode{
char data[20];
struct QNode *next;
}QNode,*QueuePtr;
typedef struct {
QueuePtr front;
QueuePtr rear;
}LinkQueue;
int main(){
Status InitQueue(LinkQueue *);
Status DestroyQueue(LinkQueue *);
Status ClearQueue(LinkQueue *);
Status QueueEmpty(LinkQueue *);
int QueueLength(LinkQueue *);
Status GetTop(LinkQueue *,char *);
Status EnQueue(LinkQueue *,char *);
Status DeQueue(LinkQueue *,char *);
void visit(char *);
Status QueueTraverse(LinkQueue *,void (*f)(char *));
LinkQueue q,*qp=&q;
InitQueue(qp);
char a[20]="你好",b[20]="C语言",c[20]="再见",d[20];
printf("当前队列长度:%d\n",QueueLength(qp));
if(QueueEmpty(qp)){
printf("当前队列为空队列\n");
}
EnQueue(qp,a);
printf("当前队列长度:%d\n",QueueLength(qp));
if(QueueEmpty(qp)){
printf("当前队列为空队列\n");
}
printf("遍历当前队列:");
QueueTraverse(qp,visit);
EnQueue(qp,b);
printf("\n当前队列长度:%d",QueueLength(qp));
if(QueueEmpty(qp)){
printf("当前队列为空队列");
}
printf("\n遍历当前队列:");
QueueTraverse(qp,visit);
GetTop(qp,d);
printf("\n获取对头元素,但是不出队列:%s",d);
EnQueue(qp,c);
printf("\n当前队列长度:%d\n",QueueLength(qp));
if(QueueEmpty(qp)){
printf("\n当前队列为空队列\n");
}
printf("遍历当前队列:");
QueueTraverse(qp,visit);
printf("\n队头元素出队列");
DeQueue(qp,d);
printf("\n当前队列长度:%d",QueueLength(qp));
if(QueueEmpty(qp)){
printf("\n当前队列为空队列\n");
}
printf("\n遍历当前队列:");
QueueTraverse(qp,visit);
if(DestroyQueue(qp)){
printf("\n队列成功销毁\n");
}
return 0;
}
Status InitQueue(LinkQueue *q){
q->front=(QueuePtr)malloc(sizeof(QNode));
if(!q->front){
exit(1);
}
q->rear=q->front;
q->rear->next=NULL;
return OK;
}
Status DestroyQueue(LinkQueue *q){
while(q->front){
q->rear=q->front->next;
free(q->front);
q->front=q->rear;
}
return OK;
}
Status ClearQueue(LinkQueue *q){
q->rear=q->front;
return OK;
}
Status QueueEmpty(LinkQueue *q){
if(q->front==q->rear){
return 1;
}else{
return 0;
}
}
int QueueLength(LinkQueue *q){
QueuePtr p=q->front;
int n=0;
while(p!=q->rear){
n++;
p=p->next;
}
return n;
}
Status GetTop(LinkQueue *q,char *e){
if(q->front==q->rear){
return ERROR;
}
QueuePtr p=q->front->next;
strcpy(e,p->data);
return OK;
}
Status EnQueue(LinkQueue *q,char *e){
QueuePtr p=(QueuePtr)malloc(sizeof(QNode));
if(!p){
exit(1);
}
strcpy(p->data,e);
p->next=NULL;
q->rear->next=p;
q->rear=p;
return OK;
}
Status DeQueue(LinkQueue *q,char *e){
if(q->front==q->rear){
return ERROR;
}
QueuePtr p=q->front->next;
strcpy(e,p->data);
q->front->next=p->next;
if(q->rear==p){
q->rear=q->front;
}
free(p);
return OK;
}
void visit(char *e){
printf("%s\t",e);
}
Status QueueTraverse(LinkQueue *q,void (*f)(char *)){
if(q->front==q->rear){
return ERROR;
}
QueuePtr p=q->front->next;
while(p!=q->rear){
f(p->data);
p=p->next;
}
f(q->rear->data);
return OK;
}