简体   繁体   中英

Singly-linked list insertion in C (pointer to pointer)

There are two versions of singly linked list insertion function.

One is common version using one pointer and it's easy to understand:

void insert(struct node *newt) {
    struct node *node = head, *prev = NULL;
    while (node != NULL && node->data < newt->data) {
        prev = node;
        node = node->next;
    }
    newt->next = node;
    if (prev == NULL)
        head = newt;
    else
        prev->next = newt;
} 

Another one is using pointer to pointer :

void insert(struct node *newt)
{
    struct node **link = &head;
    while (*link && (*link)->data < newt->data)
        link = &(*link)->next;
    newt->next = *link;
    *link = newt;     //confuse me
}

I am confused about *link = newt;Although I assign newt to *link, the previous node still point to the original address?

Thank you in advance!

When inserting a node at the front, you must update the list's head. When inserting after that, you must update the next field of the previous node. Using a pointer to node pointer does that:

At first:

struct node **link = &head;

Now link is a pointer to the head pointer. If you update *link , you update the head through that pointer.

Later:

link = &(*link)->next;

Now link is a pointer to the current node's next field. If you update *link , you update that next field.

In both cases, if you read from *link , you get the current node.

the previous node still point to the original address?

In *link = newt; it assigns newt to previous node's next member.

link either points to head or to previous node's next member.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM