亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

關于c語言初學鏈表問題,問題在注釋里?

關于c語言初學鏈表問題,問題在注釋里?

C
月關寶盒 2018-07-16 09:06:52
#include <stdio.h>#include <stdlib.h>struct node{int data;struct node *next; };struct node *add(struct node *head);//創建節點 void display(struct node *head);//輸出鏈表每項數據 int main(){char ans;struct node *mylink=NULL;printf("要加入新的節點嗎?");scanf(" %c",&ans);while(ans!='n'){mylink=add(mylink);printf("要再加入新的節點嗎?");scanf(" %c",&ans); } display(mylink);} struct node *add(struct node *head){int data;struct node *pr=(struct node *)malloc(sizeof(struct node)); if(head==NULL){head=pr;printf("輸入數據"); scanf(" %d",&(head->data));head->next=NULL;}else{struct node *p=head;while(p->next !=NULL) //這里不是也有p->next!= NULL嗎? {p=p->next;}printf("輸入數據"); scanf(" %d",&(p->data));p->next=NULL;}}void display(struct node *head){struct node *p=head;while(p != NULL) // 為什么改成 while(p->next!= NULL) 程序就會崩潰,而且不能調試,我發現在display函數里只要有 這一句程序就會崩潰,而上面的42行卻沒有問題 {printf("%d",p->data);p=p->next;}}
查看完整描述

1 回答

?
DIEA

TA貢獻1820條經驗 獲得超2個贊

  1. 把while(p != NULL)改成while(p->next!= NULL)的話,從代碼看不會有崩潰的問題,只是最后一個結點的內容打印不出來。這里的邏輯應該是while(p != NULL),結點指針不為空就輸出。

  2. 這代碼若崩潰,原因不在你說的那里,而在于函數add中的else以后的代碼邏輯錯誤,要改成如下才行——

https://img1.sycdn.imooc.com//5b59d6b50001d0c807270200.jpg

查看完整回答
反對 回復 2018-07-26
  • 1 回答
  • 0 關注
  • 773 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號