請幫我看一下這一段鏈結串列的程式碼哪邊出問題?

程式的內容是輸入五個數字用鏈結串列的方式儲存並印出來,但是我在跑的時候,輸入到第三組數字就會有問題,檢查了好多次看不出來問題出在哪,請有經驗的朋友幫我看一下,謝謝.

#include <stdio.h>
#include <stdlib.h>


struct link
{
int data;
struct link *next;
}*head,*node,*ptr;

int main(int argc, char *argv[])
{
int no,i;
head=NULL;
for(i=0;i<5;i++)
{
printf("INPUT:");
scanf("%d",&no);
node=malloc(sizeof(struct link));
if(head==NULL)
{
head=node;
node->next=NULL;
}
else
{
for(ptr=head;ptr->next!=NULL;ptr=ptr->next)
node->next=ptr->next;
ptr->next=node;
}
}
for(ptr=head;ptr!=NULL;ptr=ptr->next)
printf("\noutput\n");
printf("%d",ptr->data);
system("PAUSE");
return 0;
}
稍微看了一下,如果小弟錯誤率很高的人眼編譯器()沒看錯,應該是紅色的地方...

如果答錯,請強者繼續....

if(head==NULL)
{
head=node;
node->next=NULL;
}
else
{
for(ptr=head;ptr->next!=NULL;ptr=ptr->next) ;
node->next=ptr->next;
ptr->next=node;
}
ycweng wrote:
稍微看了一下,如果小...(恕刪)


沒有看到紅字說
一個小分號....

if(head==NULL)
{
head=node;
node->next=NULL;
}
else
{
for(ptr=head;ptr->next!=NULL;ptr=ptr->next) ; // <=====
node->next=ptr->next;
ptr->next=node;
}

if(node) //多一層保險確定有要到空間
{
if(head==NULL)
{
head=node;
//node->next=NULL; //移至上一層
ptr = head; //讓ptr指到第一點的位址
}
else
{
//for(ptr=head;ptr->next!=NULL;ptr=ptr->next)
//node->next=ptr->next;
//ptr->next=node;
我猜樓主的用意是每次都要跑一個迴圈從頭開始一直找到最後一個點的next,
但這樣太耗資源了,所以我改成以下,每次都將ptr只到最後一個點
ptr->next = node;
ptr = node;
}
node->data = no; //這裡樓主好像沒有把輸入的資料給指定進去,所以增加此行
node->next = NULL;
}
.
.
.

for(ptr=head;ptr!=NULL;ptr=ptr->next)
{ //這裡也要加括號,您應該不想只看到5個"output"吧 ^^
printf("\noutput\n");
printf("%d",ptr->data);
}

好久沒有玩鏈結了,順便複習一下
幫您修正如上,執行無誤,高手們請再指正
David_liaw0820 wrote:
if(node) /...(恕刪)


了解錯在哪了

解釋得很清楚,謝謝.
文章分享
評分
評分
複製連結

今日熱門文章 網友點擊推薦!