Delete a node in singly link list

后端 未结 3 1536
臣服心动
臣服心动 2021-02-03 12:21

How to delete a node in a singly link list with only one pointer pointing to node to be deleted?

[Start and end pointers are not known, the available information is poin

3条回答
  •  余生分开走
    2021-02-03 12:52

    You can delete a node without getting the previous node, by having it mimic the following node and deleting that one instead:

    void delete(Node *n) {
      if (!is_sentinel(n->next)) {
        n->content = n->next->content;
        Node *next = n->next;
        n->next = n->next->next;
        free(next);
      } else {
        n->content = NULL;
        free(n->next);
        n->next = NULL;
      }
    }
    

    As you can see, you will need to deal specially for the last element. I'm using a special node as a sentinel node to mark the ending which has content and next be NULL.

    UPDATE: the lines Node *next = n->next; n->next = n->next->next basically shuffles the node content, and frees the node: Image that you get a reference to node B to be deleted in:

       A           / To be deleted
      next   --->  B
                  next  --->    C
                               next ---> *sentinel*
    

    The first step is n->content = n->next->content: copy the content of the following node to the node to be "deleted":

       A           / To be deleted
      next   --->  C
                  next  --->    C
                               next ---> *sentinel*
    

    Then, modify the next points:

       A           / To be deleted
      next   --->  C       /----------------
                  next  ---|    C          |
                               next ---> *sentinel*
    

    The actually free the following element, getting to the final case:

       A           / To be deleted
      next   --->  C
                  next  --->    *sentinel*
    

提交回复
热议问题