【发布时间】:2020-05-07 18:35:44
【问题描述】:
我正在尝试练习并熟悉链表,所以我制作了这个程序来尝试创建节点并在链表的末尾添加数据。
一切正常,直到到达add_node() 函数。
我已经重做了一百万次,但我无法弄清楚它哪里出了问题。
它编译得很好,但给了我一个分段错误。
这是程序:
#include <stdio.h>
#include <stdlib.h>
struct node
{
char *card;
struct node *next;
};
typedef struct node node_t;
//print
void printlist(node_t *head)
{
node_t *temp = head;
while (temp != NULL)
{
printf("%s\n", temp->card);
temp = temp->next;
}
}
node_t *create_new_node(char *card)
{
node_t *result = malloc(sizeof(node_t));
result->card = card;
result->next = NULL;
return result;
}
node_t *insert_at_head(node_t **head, node_t *node_to_insert)
{
// have node_to_insert point to the head
node_to_insert->next = *head;
// now have the head point to the node_to_insert
*head = node_to_insert; // having this pointer requires the **head parameter
return node_to_insert;
}
// add new node at the end of the list
void add_node(node_t *head, node_t *new_node)
{
node_t *tmp = head;
while (tmp != NULL)
{
tmp = tmp->next;
}
tmp->next = new_node;
}
int main(void)
{
char *card_list[5] = {"counterspell", "black lotus", "giant growth", "mountain", "forest"};
int len = sizeof(card_list)/sizeof(card_list[0]);
node_t *head = NULL;
node_t *temporary;
for (int i = 0; i < len; i++)
{
temporary = create_new_node(card_list[i]);
if ( i == 0)
{
head = insert_at_head(&head, temporary);
}
else
{
add_node(head, temporary);
}
}
printlist(head);
return 0;
}
【问题讨论】:
-
是的,这行得通!谢谢
标签: c data-structures struct linked-list singly-linked-list