指针到指针和链表,按值传递参数

Pointer-to-Pointer and linked list, passing parameters per value

背景是我正在通过实现链表来试验 C 中的指针到指针。我的问题是关于两段代码的区别,以及为什么第一段代码给出了预期的输出,而另一段代码却没有。为什么第一段代码没有提前 head "outsite" 代码 2 似乎做的功能?

void add_node(int x, Node **head){
if(*head == NULL){
    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    *head = new_node;
} else {
    Node *n = *head;

    while(n->next != NULL){
        n = n->next;
    }

    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    n->next = new_node;
}
}

如果我添加 4 个元素并在每次添加后打印列表,则输出符合预期: 1 | 12 | 123 | 1234

void add_node(int x, Node **head){
if(*head == NULL){
    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    *head = new_node;
} else {
    while((*head)->next != NULL){
        *head = (*head)->next;
    }

    Node *new_node = (Node*) malloc(sizeof(new_node));
    new_node->x = x;
    (*head)->next = new_node;
}
}

输出如下:1 | 12 | 23 | 34

评估输入 1、2、3 并关注头部。

while((*head)->next != NULL){
    *head = (*head)->next;
}
Node *new_node = (Node*) malloc(sizeof(new_node));
        new_node->x = x;
        (*head)->next = new_node;

让头指向某处,您的输出所描绘的就是这个地方 ;)

输入1和1,2条件不满足,你逃跑了。

在第一个示例中,您使用指针 n 遍历链表,将其分配给 n->next,这正是您要遍历链表所要做的。 在第二个示例中,您正在更改头指针指向的内容:

*head = (*head)->next;

您实际上是将链表的开头移动到另一个节点,这就是您出现这种行为的原因。