作者jeffchen106 (超哥)
看板C_and_CPP
標題[問題] Linked list insert node卡關
時間Fri Aug 13 22:42:58 2021
開發平台(Platform): (Ex: Win10, Linux, ...)
Win 1-
編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出)
https://www.programiz.com/c-programming/online-compiler/
問題(Question):
各位板友大大家好, 小弟有一題linked list卡關了。想請問各位板友
主要是關於寫副程式可以新增linked list的node, 傳入值是node的數量
,並且再用另一個副程式印出來。
但後來發現似乎insert node這邊就沒有成功了,一直顯示Segmentation fault..
使用的編譯器是Online compiler:
https://www.programiz.com/c-programming/online-compiler/
希望好心的高手幫忙我看一下,謝謝!!
程式碼如下:
// Online C compiler to run C program online
#include <stdio.h>
// Input: {240, 301, 479, 884, 856, 623, 905, 270, 981, 371}
// Output: mid value: 856, largest value: 884
#include <stdlib.h>
struct node {
int data;
struct node *next;
};
typedef struct node Node;
void insert_node(int num, Node *head_node)
{
while(num >0)
{
printf("333");
Node *newNode = malloc(sizeof(struct node));
head_node -> next = newNode;
head_node = newNode;
num --;
printf("444");
}
}
void gen_test_case(int data_num, Node *head_node)
{
printf("222");
insert_node(data_num, head_node);
}
void show_test_case(int print_num, Node *head_node)
{
printf("555");
for (int i=0; i< print_num; i++)
{
printf("%d\n", head_node -> data);
head_node = head_node->next;
printf("666");
}
}
// void find_middle_node()
// {
// }
int main(void)
{
Node *head_node = NULL;
Node *last_node = NULL;
printf("111");
insert_node(1, head_node);
gen_test_case(10, head_node);
printf("666");
show_test_case(10, head_node);
//find_middle_node();
return 0;
}
餵入的資料(Input):
預期的正確結果(Expected Output):
錯誤結果(Wrong Output):
程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔)
補充說明(Supplement):
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 219.71.109.75 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1628865781.A.B20.html
推 LPH66: insert_node 當中對 head_node 的改動沒有傳出來 08/13 22:54
→ LPH66: 請傳入這個指標的指標以改動你要的指標值 08/13 22:54
推 elysium5290: main()傳入了head_node是null ptr, 爾後對其derefer 08/13 23:51
→ elysium5290: ence了(head_node->next)自然會crashed. 08/13 23:51
→ smartclever: head_node要兩顆星 08/16 20:53