【发布时间】:2018-04-19 02:14:36
【问题描述】:
我有这个练习,要求我创建一个函数,该函数根据包含一个整数的结构将新节点中的数字添加到链表的头部。这是结构:
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 本身。如果有人能向我解释原因,我会很高兴,谢谢。
【问题讨论】:
-
在C++中有containers。
-
1) std::list & std::forward_list 已经存在 - 使用它们。 2) 对于现代计算机而言,链表通常是一种可怕的数据结构(std::vector 几乎总是更好的选择。
-
选择一种语言,C 或 C++。
-
@Paul @Bilal 通过删除任何初始标签来使现有答案无效并不是很好。虽然我的回答仍然涵盖了你问题的 c 部分。
标签: c algorithm data-structures linked-list