链队列,模拟病人看病——有源码
代码:
- C/C++ code
#include<stdio.h>#include<malloc.h>typedef struct node{int data;struct node *next;}QNode;typedef struct {QNode *front,*rear;}LQueue;/*创建带头结点的空对////////////////////////////////////////////////////////////////*/LQueue *Init(LQueue *q){QNode *p;q=malloc(sizeof(LQueue));p=malloc(sizeof(QNode));p->next=NULL;q->front=p;q->rear=p;return q;}/*入队////////////////////////////////////////////////////////////////////////////////*/void In(LQueue *q,int x){QNode *p;p=malloc(sizeof(QNode));p->data=x;p->next=NULL;q->rear->next=p;q->rear=p;}/*判队空///////////////////////////////////////////////////////////////////////////////*/int Empty(LQueue *q){if(q->front=q->rear)return 0;elsereturn 1;}/*出队////////////////////////////////////////////////////////////////////////////////*/int Out(LQueue *q,int *x){QNode *p;p=malloc(sizeof(LQueue));if(Empty(q)){printf("队空!");return 0;}else{p=q->front;q->front->next=p->next;*x=p->data;if(q->front->next==NULL) {q->rear=q->front;}free(p);return 1;}}void main(){ LQueue *q; int flag,n; char ch; q=Init(q); flag=1; while(flag) { printf("\n请输入命令:\n"); ch=getchar(); fflush(stdin); switch(ch) { case 'a': printf("\n病历号:\n"); scanf("%d",&n); fflush(stdin); In(q,n); break; case 'n': if(!Empty(q)) { Out(q,&n); printf("\n病历号为%d的病人就诊!\n",n); } else { printf("\n无病人等候就诊!"); } break; case 'q': printf("\n停止挂号,下列病人依次就诊:\n"); while(q->front->next!=NULL) { Out(q,&n); printf("\n病历号为%d的病人就诊!\n",n); } flag=0; break; default: printf("\n无效命令!\n"); break; } }}
问题:
1-明明是队列,为什么输出就诊病号的时候按照栈的机制后进先出了?
2-出队操作else语句里面书上源码是p=q->front->next;但是实际上这样不对。可是入队操作的时候明明有一个空节点的,q->front应该是这个空节点才对。q->front->next也应该是空节点的next才对,为什么这里p=q->front->next却错误呢?
[解决办法]
我表示这样的代码在VS下都不能通过编译。楼主是用的TC咩!
[解决办法]
那你为什么不直接贴个能在VC里正确编译的呢?malloc前面的类型不写。而且还有指针什么的强制赋值的呢。我看了你的结构体的定义。QNode和LQueue根本就不是一回事,为什么你可以这样呢??
QNode *p;
p=malloc(sizeof(LQueue));