#include<stdio.h> #include<malloc.h> typedef struct queue { int data; struct queue *link; }QUEUE; void EnQueue(QUEUE **head,QUEUE**tail,int x) { //从队尾tail进队 QUEUE *p; p=(QUEUE*)malloc(sizeof(QUEUE)); p->data=x; p->link=NULL; if(*head==NULL) *head=*tail=p;//*head=p;若不加tail插入第二个元素时会报错 else{ (*tail)->link=p; *tail=p; } } int DeQueue(QUEUE **head,QUEUE**tail,int*cp) { //从队头head出队 QUEUE *p; p=*head; if(*head==NULL) return 1; *cp=(*head)->data; //*head=p->link;和*head=(*head)->link都是可以的 *head=(*head)->link; if(*head==NULL) *tail=NULL; free(p); return 0; } void OutputQueue(QUEUE *head) { while(head!=NULL) { printf("%d ",head->data);//控制显示时有空白位置 要留空 head=head->link; } printf("\n"); } void main() { QUEUE *head,*tail; int op,i; head=tail=NULL;//空队列 while(1) { printf("请选择操作。1:进队 2:出队 0:退出"); fflush(stdin); scanf("%d",&op); switch(op) { case 0:return; case 1: printf("请输入进队元素:"); scanf("%d",&i); EnQueue(&head,&tail,i); printf("队内元素为: \n"); OutputQueue(head); break; case 2:if(DeQueue(&head,&tail,&i)==0) { printf("出队元素为:[%d],队内元素为: \n",i); OutputQueue(head); } else printf("队空 \n"); break; } } }