【发布时间】:2021-09-20 16:51:35
【问题描述】:
我正在阅读有关 C++ 链接列表的教程。我发现以下代码用于在链接列表中插入元素的实现:
/* Given a reference (pointer to pointer) to the head
of a list and an int, appends a new node at the end */
void append(Node** head_ref, int new_data)
{
/* 1. allocate node */
Node* new_node = new Node();
Node *last = *head_ref; /* used in step 5*/
/* 2. put in the data */
new_node->data = new_data;
/* 3. This new node is going to be
the last node, so make next of
it as NULL*/
new_node->next = NULL;
/* 4. If the Linked List is empty,
then make the new node as head */
if (*head_ref == NULL)
{
*head_ref = new_node;
return;
}
/* 5. Else traverse till the last node */
while (last->next != NULL)
last = last->next;
/* 6. Change the next of last node */
last->next = new_node;
return;
}
在第 1 步中,我们声明了一个名为 new_node 的指针,它指向一个动态创建的块。
我无法理解的是,如果函数被调用 4 次,那么如何在每次调用时创建一个具有相同名称的新指针变量?由于我们使用的是动态内存分配,所以当我们从函数返回时它不会被转储。
那么,这段代码是如何工作的?
【问题讨论】:
-
因为这是按设计工作,而其他一些函数负责
deleteing 链表中的所有内存? -
new不创建变量;它创建对象。new_node与任何其他局部变量没有区别;它恰好指向一个具有动态生命周期的对象。
标签: c++ pointers linked-list dynamic-memory-allocation