#include<stdio.h> #include<Stdlib.h> typedef int elemtype; typedef struct QueueNode { elemtype data; struct QueueNode *next; }LinkedQueueNode; typedef struct LQueue { LinkedQueueNode *front; LinkedQueueNode *rear; }LQueue, * LinkedQueue; LinkedQueue Init_LinkedQueue(); int LinkedQueue_Empty(LinkedQueue Q); int Enter_LinkedQueue(LinkedQueue Q,elemtype x); int Delete_LinkedQueue(LinkedQueue Q,elemtype *x); int GetFront_LinkedQueue(LinkedQueue Q,elemtype *x); int Print_LinkedQueue(LinkedQueue Q); void menu() { system("cls"); printf(" 1-创建 "); printf(" 2-入队 ");; printf(" 3-判断队列是否为空 "); printf(" 4-出队 "); printf(" 5-查看队头元素 "); printf(" 6-输出 "); printf(" #-quit "); printf("Please select: "); } int main() { char cmd; int isdo; LinkedQueue Q; elemtype x; system("cls"); menu(); while((cmd=getchar())!='#') { switch(cmd) { case '1': Q=Init_LinkedQueue(); if(Q==NULL) { printf("申请链队列内存空间失败,程序结束"); return 0; } printf(" 创建成功! "); printf(" "); break; case '2': printf("输入队列元素: "); scanf("%d",&x); while(x!=0) { isdo= Enter_LinkedQueue(Q,x); scanf("%d",&x); } if(isdo==1) { printf("入队成功"); } else { printf("入队失败"); } printf(" "); printf(" "); break; case '3': isdo=LinkedQueue_Empty(Q); if(isdo==1) { printf("队列为空 "); } else if(isdo==0) { printf("队列不为空 "); } printf(" "); printf(" "); break; case '4': isdo=Delete_LinkedQueue(Q,&x); if(isdo==1) { printf("出队成功,出队的元素为:%d ",x); } else if(isdo==0) { printf("出队失败 "); } printf(" "); printf(" "); break; case '5': isdo=GetFront_LinkedQueue(Q,&x); if(isdo==1) { printf("队头元素为:%d ",x); } else if(isdo==0) { printf("取队头元素失败 "); } printf(" "); printf(" "); break; case '6': isdo=Print_LinkedQueue(Q); printf(" "); printf(" "); break; } fflush(stdin); system("pause"); menu(); } return 0; } //初始化 LinkedQueue Init_LinkedQueue() { LinkedQueue Q=(LinkedQueue)malloc(sizeof(LQueue)); LinkedQueueNode *head=(LinkedQueueNode *)malloc(sizeof(LinkedQueueNode)); if(head!=NULL&&Q!=NULL) { head->next=NULL; Q->front=head; Q->rear=head; } return Q; } //判队列空 int LinkedQueue_Empty(LinkedQueue Q) { if(Q->front==Q->rear) { return 1; } else { return 0; } } //入队 int Enter_LinkedQueue(LinkedQueue Q,elemtype x) { LinkedQueueNode *node; node=(LinkedQueueNode *)malloc(sizeof(LinkedQueueNode)); if(node==NULL) { return 0; } node->data=x; node->next=NULL; Q->rear->next=node; //将新结点插入队尾 Q->rear=node; //设置尾指针指向新的队尾元素 return 1; } //出队 int Delete_LinkedQueue(LinkedQueue Q,elemtype *x) { LinkedQueueNode *node; if(Q->front==Q->rear) { return 0; } else { node=Q->front->next; *x=node->data; Q->front->next=node->next; if(node==Q->rear) { Q->rear=Q->front; } free(node); return 1; } } //取队列头数据元素 int GetFront_LinkedQueue(LinkedQueue Q,elemtype *x) { if(Q->front==Q->rear) { return 0; } else { *x=Q->front->next->data; return 1; } } //输出 int Print_LinkedQueue(LinkedQueue Q) { LinkedQueueNode *p; if(Q->front==Q->rear) { return 0; } p=Q->front->next; while(p!=0) { printf("%4d ",p->data); p=p->next; } return 1; }