看板 C_and_CPP 關於我們 聯絡資訊
謝謝板友的提示。我將程式修改了一下,原本卡關的地方有過。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
NciscalA: insert node 裡面加新的 node 之後 head_node 沒更新, 08/14 12:37
NciscalA: 變成一直重新覆蓋第二個 node,所以產生的 linked lis 08/14 12:37
NciscalA: t 長度只有 2。 08/14 12:37
PXTERHUA: insert_node裡的head_node->next = newNode;前一行加個 08/14 16:42
PXTERHUA: last_node = head_node->next;就勉強可以動了,原理是 08/14 16:42
PXTERHUA: 要有人負責暫時接住head_node->next,否則執行head_nod 08/14 16:42
PXTERHUA: e->next = newNode;後原本的head_node->next就被弄丟了 08/14 16:42
PXTERHUA: 但要改的東西還很多,像其實不需要讓last_node當引數; 08/14 16:51
PXTERHUA: insert的迴圈應該放到gen;如果需要更換head可能要嘗試 08/14 16:51
PXTERHUA: 用double pointer或其他方法 08/14 16:51
elysium5290: 錯誤的原因前面幾樓大大已經回覆了 08/15 04:06
elysium5290: 但我認為你應該先思考一下是什麼原因設計了 08/15 04:06
elysium5290: head_node及last_node,以紀錄頭尾作為目的的話 08/15 04:06
elysium5290: 你現在的寫法整體是有點怪異的 08/15 04:06
jeffchen106: 謝謝~~我再研究一下 :) 08/15 07:07