简体   繁体   中英

How can I delete an node from a linked list with a single pointer?

The book I study #include an exercise that asks us for modifying the following code which deletes a node from a linked list and building another function that does the exact thing with only one pointer:

struct node {
    int value;
    struct node * next;
};

struct node delete_from_list( struct node * list , int n){
struct node *cur, *prev;

for (cur = list, prev = NULL;
    cur != NULL && cur -> value != n;
    prev = cur, cur -> next)
;

if(cur == NULL)
    return list;
else if(prev == NULL)
    list = list -> next;
else
prev -> next = cur -> next;

free(cur);
return list;
}

Some code I've seen online is:

struct node *delete_from_list(struct node **list, int n) {
    struct node *entry = *list;
    while (entry) {
        if (entry->value == n) {
            *list = entry->next;
            free(entry);
            break;
        }
        list = &entry->next;
        entry = entry->next;
    }
    return *list;
}

But i have two objections for this:

  1. This code contains two pointers actually entry and list .

  2. We are free() ing the entry yet proceed to use it which "feels" like an error.

Please, if you are willing to help, either explain my objections or write a new code. Thanks.

  1. This code contains two pointers actually entry and list .

You are required to build an algorithm that uses a single pointer. In your case, though it seems like two, entry is that one pointer which the algorithm uses apart from list which is actually an input to the function containing the algorithm .

  1. We are free() ing the entry yet proceed to use it which "feels" like an error.

The code doesn't use entry after freeing it. Once freed, the loop breaks immediately due to the break statement succeeding the call to free .

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