程式的內容是輸入五個數字用鏈結串列的方式儲存並印出來,但是我在跑的時候,輸入到第三組數字就會有問題,檢查了好多次看不出來問題出在哪,請有經驗的朋友幫我看一下,謝謝.
#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; //移至上一層
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);
}
好久沒有玩鏈結了,順便複習一下
幫您修正如上,執行無誤,高手們請再指正
)沒看錯,應該是紅色的地方...


























































































