在链接列表中插入节点

时间:2017-11-06 20:17:29

标签: c algorithm data-structures linked-list

我有这个练习,要求我创建一个函数,它根据包含一个整数的结构将新节点中的数字添加到链表的头部。这是结构:

struct Node
{
    int data;
    struct Node *next;
};
直到现在还没问题。所以我创建了一个带有2个参数的参数:要添加的整数和指向链表头部的指针,但它不起作用。这是我的代码:

void push(struct Node* head, int new_data)
{
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    new_node->data = new_data;

    new_node->next = head;

    head = new_node;
}

所以,我做的是我将 new_node 指向 head 所指向的同一节点,之后我将新节点作为链接的新头名单。这似乎很合乎逻辑,虽然它不起作用。另一方面,当我给函数指定 head 指针的地址而不是指针本身时,它确实有效:

void push(struct Node** head_ref, int new_data)
{
    /* 1. allocate node */
    struct Node* new_node = (struct Node*) malloc(sizeof(struct Node));

    /* 2. put in the data  */
    new_node->data  = new_data;

    /* 3. Make next of new node as head */
    new_node->next = (*head_ref);

    /* 4. move the head to point to the new node */
    (*head_ref)    = new_node;
}

这是双**的函数的主要内容:

int main()
{
    struct Node* head = NULL;
    push(&head,7);
    push(&head,6);
    push(&head,3);
    return 0;
}

我理解第二个功能应该有效,但我不明白为什么有必要使用 head 的地址而不是 head 本身。如果有人能向我解释原因,我会很高兴,谢谢。

1 个答案:

答案 0 :(得分:2)

  

但我不明白为什么有必要使用头部的地址而不是头部。

在普通的代码中,你不能有引用(与c ++相反),而只是指针。

head指针变量中存储的值应该从调用push()中更改,因此您需要传递head变量的地址来更改({* 1}}指针)值。

int main()
{
    struct Node* head = NULL;
    push(&head,7);
    // ...
}
void push(struct Node** head_ref, int new_data)
{

    // ...

    /* 3. Make next of new node as head */
    new_node->next = (*head_ref); // Dereferencing head_ref yields the current 
                                  // content of head

    /* 4. move the head to point to the new node */
    (*head_ref)    = new_node; // Store the newly allocated memory address
                               // into the head pointer
}

当您使用c ++代码标记问题时,这是不必要的。

您也可以通过引用获取指针参数:

void push(struct Node*& head_ref, int new_data)
                   // ^
{
    // ...

    /* 3. Make next of new node as head */
    new_node->next = head_ref;

    /* 4. move the head to point to the new node */
    head_ref = new_node; // <<<<<<<<<<
}
int main() {
    struct Node* head = nullptr;
    push(head,7);
    push(head,6);
    push(head,3);
    return 0;
}
相关问题