指向C++指针的指针
问题描述:
在这个程序中,为什么我不能使用* head = * head-> next在更改头部行?指向C++指针的指针
这是一个geeksforgeek算法...
或请建议我一些很好的教程来学习指针
void deleteNode(struct node **head_ref, int key)
{
// Store head node
struct node* temp = *head_ref, *prev;
// If head node itself holds the key to be deleted
if (temp != NULL && temp->data == key)
{
*head_ref = temp->next; // Changed head
free(temp); // free old head
return;
}
// Search for the key to be deleted, keep track of the
// previous node as we need to change 'prev->next'
while (temp != NULL && temp->data != key)
{
prev = temp;
temp = temp->next;
}
// If key was not present in linked list
if (temp == NULL) return;
// Unlink the node from linked list
prev->next = temp->next;
free(temp); // Free memory
}
答
您可以使用*head_ref = *head_ref->next
。
但使用temp
只是为了保持清楚。如果您使用temp->data
进行比较,然后使用*head_ref
进行删除,则看起来有点模糊。
如果您确实想使用*head_ref
,那么您可以更改代码以使其看起来更清晰。像,
// If head node itself holds the key to be deleted
if (*head_ref != NULL && *head_ref->data == key)
{
*head_ref = *head_ref->next; // Changed head
free(temp); // free old head
return;
}
+0
这不起作用,但我想出了解决方案(* head) - > next。没有支架是行不通的 –
我认为'* head = * head-> next'应该可以工作,你试过吗?但是temp也可以用于其他目的 – keyser