指向C ++中的指针

时间:2016-07-14 18:25:44

标签: algorithm pointers data-structures

在这个程序中为什么我不能在更改标题行中使用 * head = * head-> next

这是一个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
}

1 个答案:

答案 0 :(得分:0)

您可以使用*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;
}