Re: [問題] Linked list insert node卡關

看板C_and_CPP作者 (超哥)時間2年前 (2021/08/14 08:04), 編輯推噓3(3012)
留言15則, 4人參與, 2年前最新討論串2/2 (看更多)
謝謝板友的提示。我將程式修改了一下,原本卡關的地方有過。insert_node有成功, 但show_test_case的function,也就是要印出這些linked list的function,卻又卡關。 卡關的地方是,他show了兩筆之後就說segmentation fault,而且show的資料看起來 都是head而沒有後面的node。 使用https://www.programiz.com/c-programming/online-compiler/ 編譯的結果: /tmp/kKVJ6xsdfM.o 1 1 Segmentation fault 我上網查了類似的case,寫法幾乎都跟我一樣啊@@.... 希望好心的高手大大能再教我一下,感激不盡 修改後的code: struct node { int data; struct node *next; }; typedef struct node Node; void insert_node(int num, Node *head_node, Node *last_node) { while(num >0) { Node *newNode = malloc(sizeof(Node)); newNode-> data = num; head_node -> next = newNode; newNode -> next = last_node; // printf("%d\n", head_node -> data); num --; } } void gen_test_case(int data_num, Node *head_node, Node *last_node) { insert_node(data_num, head_node, last_node); } void show_test_case(int print_num, Node *head_node) { Node *iteration; iteration = head_node; for (int i=0; i< print_num; i++) { printf("%d\n", iteration -> data); iteration = iteration-> next; } } // void find_middle_node() // { // } int main(void) { Node *head_node = NULL; Node *last_node = NULL; head_node = malloc(sizeof(Node)); head_node -> data = 1; head_node -> next = last_node; gen_test_case(3, head_node, last_node); show_test_case(3, head_node); //find_middle_node(); return 0; } -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.71.109.75 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1628899494.A.BB8.html

08/14 12:37, 2年前 , 1F
insert node 裡面加新的 node 之後 head_node 沒更新,
08/14 12:37, 1F

08/14 12:37, 2年前 , 2F
變成一直重新覆蓋第二個 node,所以產生的 linked lis
08/14 12:37, 2F

08/14 12:37, 2年前 , 3F
t 長度只有 2。
08/14 12:37, 3F

08/14 16:42, 2年前 , 4F
insert_node裡的head_node->next = newNode;前一行加個
08/14 16:42, 4F

08/14 16:42, 2年前 , 5F
last_node = head_node->next;就勉強可以動了,原理是
08/14 16:42, 5F

08/14 16:42, 2年前 , 6F
要有人負責暫時接住head_node->next,否則執行head_nod
08/14 16:42, 6F

08/14 16:42, 2年前 , 7F
e->next = newNode;後原本的head_node->next就被弄丟了
08/14 16:42, 7F

08/14 16:51, 2年前 , 8F
但要改的東西還很多,像其實不需要讓last_node當引數;
08/14 16:51, 8F

08/14 16:51, 2年前 , 9F
insert的迴圈應該放到gen;如果需要更換head可能要嘗試
08/14 16:51, 9F

08/14 16:51, 2年前 , 10F
用double pointer或其他方法
08/14 16:51, 10F

08/15 04:06, 2年前 , 11F
錯誤的原因前面幾樓大大已經回覆了
08/15 04:06, 11F

08/15 04:06, 2年前 , 12F
但我認為你應該先思考一下是什麼原因設計了
08/15 04:06, 12F

08/15 04:06, 2年前 , 13F
head_node及last_node,以紀錄頭尾作為目的的話
08/15 04:06, 13F

08/15 04:06, 2年前 , 14F
你現在的寫法整體是有點怪異的
08/15 04:06, 14F

08/15 07:07, 2年前 , 15F
謝謝~~我再研究一下 :)
08/15 07:07, 15F
文章代碼(AID): #1X5mYcku (C_and_CPP)
文章代碼(AID): #1X5mYcku (C_and_CPP)