#include <stdio.h>#include <malloc.h>#include <stdlib.h>typedef int QElemType;typedef struct QNode {QElemType data;struct QNode *next;}QNode;typedef struct{QNode *front,*rear;}LinkQueue;void enQueue(LinkQueue *Q, QElemType e);/*入隊列操作*/void delQueue(LinkQueue *Q,QElemType *e);/*出隊列操作*/void printQueue(LinkQueue *Q);/*依次輸出隊列*/main(){LinkQueue *myQueue;QNode *s;QElemType elem;myQueue=(LinkQueue *)malloc(sizeof(LinkQueue));s=(QNode *)malloc(sizeof(QNode));s->next=NULL;myQueue->front=myQueue->rear=s;enQueue(myQueue,5);enQueue(myQueue,7);enQueue(myQueue,9);delQueue(myQueue, &elem);printf("出隊列的元素為:%d\n",elem);printQueue(myQueue);}void enQueue(LinkQueue *Q, int e)/*入隊列操作*/{QNode *s;s=(QNode *)malloc(sizeof(QNode));s->data=e;s->next=NULL;Q->rear->next=s;Q->rear=s;}void delQueue(LinkQueue *Q, int *e)/*出隊列操作,將刪除的結點值保存在參數*e中*/{ QNode *s;if(Q->front==Q->rear){printf("隊列為空!");exit(1);}s=Q->front->next;*e=s->data;Q->front->next=Q->front->next->next;free(s);}void printQueue(LinkQueue *Q)/*依次輸出隊列*/{if(Q->front==Q->rear){printf("隊列為空");exit(1);}while(Q->front!=Q->rear)/*老師告訴我說是這里的while是死循環,為什么是死循環呢,不是很懂,請細說。請幫我改為正確的代碼,謝謝。*/{printf("%d, ", Q->front->next->data);Q->front->next=Q->front->next->next;}exit(0);}
2 回答

慕無忌1623718
TA貢獻1744條經驗 獲得超4個贊
黑色的提示框是程序運行結果窗口,不是錯誤的窗口
代碼錯誤說明如下:
while (Q->front!=Q->rear) //在本循環體之中,Q->front Q->rear的值始終沒有變化 //故而在這里肯定是一個死循環 { printf ( "%d, " , Q->front->next->data); Q->front->next=Q->front->next->next; } //改正后的代碼如下: QNode* s = Q->front; while (s!=Q->rear) { printf ( "%d, " , s->data); s=s->next; } |
另外,所有的函數當中不應該有exit
exit是一個系統函數,表示結束程序,而不是退出函數
如果需要退出函數可以使用return來達到該目的

POPMUISE
TA貢獻1765條經驗 獲得超5個贊
你的代碼是想把front到rear的值全部輸出
但是你下面的操作自己檢查一下沒有改變front的值,也沒有改變rear的值,所以front!=rear是死循環
如果好一點的話
void printQueue(LinkQueue *Q)/*依次輸出隊列*/
{
if(Q->front==Q->rear)
{
printf("隊列為空");
exit(1);
}
while(Q->front!=Q->rear)/*老師告訴我說是這里的while是死循環,為什么是死循環呢,不是很懂,請細說。請幫我改為正確的代碼,謝謝。*/
{
printf("%d, ", Q->front->data);
Q->front=Q->front->next;
}
//exit(0);
}試試可不可以
- 2 回答
- 0 關注
- 161 瀏覽
添加回答
舉報
0/150
提交
取消