【发布时间】:2019-04-02 03:38:48
【问题描述】:
这可能是一个愚蠢的问题,但我真的很想知道为什么会这样。当试图为链表创建附加函数时,为什么这个单指针解决方案不起作用,但是当使用双指针时它起作用?
单指针:
void append(node *head, int value){
node *current = head;
node *new = malloc(sizeof(node));
if (new == NULL){
printf("couldn't allocate memory");
return;
}
new->value = value;
new->next = NULL;
if (head == NULL){
head = new;
return;
}
while (current->next != NULL)
current = current->next;
current->next = new;
return;}
双指针:
void append(node **head, int value){
node *current = *head;
node *new = malloc(sizeof(node));
if (new == NULL){
printf("couldn't allocate memory");
return;}
new->value = value;
new->next = NULL;
if (*head == NULL){
*head = new;
return;
}
while (current->next != NULL)
current = current->next;
current->next = new;
return;}
【问题讨论】:
标签: c linked-list