下面的两个代码示例都在链接列表的顶部添加了一个节点.但是,第一个代码示例使用双指针,而第二个代码示例使用单个指针
代码示例1:
struct node* push(struct node **head, int data)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = *head;
return newnode;
}
push(&head,1);
Run Code Online (Sandbox Code Playgroud)
代码示例2:
struct node* push(struct node *head, int data)
{
struct node* newnode = malloc(sizeof(struct node));
newnode->data = data;
newnode->next = head;
return newnode;
}
push(head,1)
Run Code Online (Sandbox Code Playgroud)
两种策略都有效.但是,许多使用链表的程序使用双指针来添加新节点.我知道双指针是什么.但是如果单个指针足以添加新节点,为什么很多实现都依赖于双指针?
有没有一个指针不起作用的情况所以我们需要去一个双指针?