// queue.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include #include #include #include //定义链队节点类型 typedef struct LinkQueueNode { int data; struct LinkQueueNode * next; }LinkQueueNode; //定义链队类型 typedef struct LinkQueue { LinkQueueNode *front,*rear; }LinkQueue; //初始化队列 void InitQueue(LinkQueue *lq) { LinkQueueNode *p; p=(LinkQueueNode *)malloc(sizeof(LinkQueueNode)); lq->front=p; lq->rear=p; (lq->front)->next=NULL; } //入队,入队节点值为x void EnterQueue(LinkQueue * lq,int x) { LinkQueueNode *p; p=(LinkQueueNode *)malloc(sizeof(LinkQueueNode)); p->data=x; p->next=NULL; (lq->rear)->next=p; lq->rear=p; } //出队,出队节点值为x OutQueue(LinkQueue *lq,int *x) { LinkQueueNode *s; if(lq->front==lq->rear) { printf("队空"); return 0; } else { s=(lq->front)->next; *x=s->data; (lq->front)->next=s->next; if(s->next==NULL) lq->rear=lq->front; free(s); return 1; } } //判断队列是否为空 EmptyQueue(LinkQueue lq) { if(lq.rear==lq.front) return 1; else return 0; } //取队列头节点,队头节点值为x GetHead(LinkQueue lq,int *x) { LinkQueueNode *p; if(lq.rear==lq.front) return 0; else { p=lq.front->next; *x=p->data; return 1; } } void main() { LinkQueue lq; int n; char ch; InitQueue(&lq); while(1) { printf("\n请输入命令 A 入队; O 出队 L 显示队列内容:\n"); scanf("%c",&ch); switch(toupper(ch)) { case 'A': printf("请输入节点值,节点准备入队\n"); scanf("%d",&n); EnterQueue(&lq,n); break; case 'O': if(!EmptyQueue(lq)) { OutQueue(&lq,&n); printf("值为%d的节点出队",n); } else printf("队列为空\n"); break; case 'L': printf("下列节点依次出队\n"); break; } if(toupper(ch)=='L') { while(!EmptyQueue(lq)) { OutQueue(&lq,&n); printf("值为%d的节点出队\n",n); } break; } } }