Deleting a middle node from a single linked list when pointer to the previous node is not available

前端 未结 24 1372
陌清茗
陌清茗 2020-11-29 20:42

Is it possible to delete a middle node in the single linked list when the only information available we have is the pointer to the node to be deleted and not the pointer to

24条回答
  •  情话喂你
    2020-11-29 21:12

    Let's assume a list with the structure

    A -> B -> C -> D

    If you only had a pointer to B and wanted to delete it, you could do something like

    tempList = B->next;
    *B = *tempList;
    free(tempList);
    

    The list would then look like

    A -> B -> D

    but B would hold the old contents of C, effectively deleting what was in B. This won't work if some other piece of code is holding a pointer to C. It also won't work if you were trying to delete node D. If you want to do this kind of operation, you'll need to build the list with a dummy tail node that's not really used so you guarantee that no useful node will have a NULL next pointer. This also works better for lists where the amount of data stored in a node is small. A structure like

    struct List { struct List *next; MyData *data; };
    

    would be OK, but one where it's

    struct HeavyList { struct HeavyList *next; char data[8192]; };
    

    would be a bit burdensome.

提交回复
热议问题