Var*_*pta 2 c c++ pointers data-structures
void addNewNode (struct node *head, int n)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> data = n;
temp -> link = head;
head = temp;
}
Run Code Online (Sandbox Code Playgroud)
上面给出的代码是用于在链表头部添加新节点的功能的普遍错误版本.通常正确的版本是,像,
void addNewNode (struct node **head, int n);
void addNewNode (struct node * &head, int n);
Run Code Online (Sandbox Code Playgroud)
我为了这个目的而制定了另一个但很简单的功能.
struct node* addNewNode (struct node *head, int n)
{
struct node* temp = (struct node*) malloc(sizeof(struct node));
temp -> data = n;
temp -> link = head;
return temp;
}
Run Code Online (Sandbox Code Playgroud)
但我还没有看到在代码和教程中使用或讨论过这个问题,因此我很想知道这种方法是否有一些缺陷.