關於C語言實做鏈結串列的問題

2009-04-25 6:01 am
下面是我實做鏈結串列,輸入數字後用鏈結串列的方式串起來,並且可以選擇要刪除鏈結中頭中尾的數值,但是有一點問題想請教:

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

struct link
{
int data;
struct link *next;
}*head,*node,*ptr,*temp; //如果這邊用全域變數的方式宣告
//我的副程式呼叫方式正確嗎?
int main(int argc, char *argv[])
{
int no,del;
printf("連續輸入數字,按Ctrl+z結束\n");
while(scanf("%d",&no)!=EOF)
{
node=malloc(sizeof(struct link));
node->data=no;
if(node==NULL)
printf("沒有拿到記憶體\n");
else if(head==NULL)
{
ptr=head=node;
node->next=NULL;
}
else
{
ptr->next=node;
node->next=NULL;
ptr=node;
}
}
printf("鏈結串列輸出:");
list_node();
printf("要刪除哪一個數字:");
scanf("%d",&del);
find_node(del);
list_node();
system("PAUSE");
return 0;
}

int list_node()
{
for(ptr=head;ptr!=NULL;ptr=ptr->next)
printf("%d",ptr->data);
printf("\n");
}

int find_node(int del)
{
ptr=head;
if(ptr->data==del)
{
ptr=ptr->next;
free(head);
head=ptr;
}
else
{
for(ptr=head;ptr->next!=NULL;ptr=ptr->next)
{
if(ptr->next->data==del)
{
if(ptr->next==NULL) //刪除最後一個節點的時候程式會有問題,
ptr->next=NULL; //這兩行出了問題嗎?
else
{
temp=ptr;
temp=ptr->next->next;
ptr->next=temp;
}
}
}
}
}

回答 (2)

2009-04-26 8:04 am
✔ 最佳答案
我幫你修改一下for迴圈裡的程式
主要是你在第二個if判斷錯了
我也幫你修改了一下else裡面的程式
修改過的程式如下

if(ptr->next->data==del)
{
if(ptr->next->next==NULL) //刪除最後一個節點的時候程式會有問題,
{
free(ptr->next);
ptr->next=NULL; //這兩行出了問題嗎?
break;
}
else
{
temp=ptr->next;
ptr->next=temp->next;
free(temp);
}

希望對你有幫助
參考: 我自己
2009-04-25 2:31 pm
There are a few problems with this program. Can I answer this in English?


收錄日期: 2021-04-30 12:59:01
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090424000016KK09584

檢視 Wayback Machine 備份