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

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


It's definitely more a quiz rather than a real problem. However, if we are allowed to make some assumption, it can be solved in O(1) time. To do it, the strictures the list points to must be copyable. The algorithm is as the following:

We have a list looking like: ... -> Node(i-1) -> Node(i) -> Node(i+1) -> ... and we need to delete Node(i).

  1. Copy data (not pointer, the data itself) from Node(i+1) to Node(i), the list will look like: ... -> Node(i-1) -> Node(i+1) -> Node(i+1) -> ...
  2. Copy the NEXT of second Node(i+1) into a temporary variable.
  3. Now Delete the second Node(i+1), it doesn't require pointer to the previous node.

Pseudocode:

void delete_node(Node* pNode){    pNode->Data = pNode->Next->Data;  // Assume that SData::operator=(SData&) exists.    Node* pTemp = pNode->Next->Next;    delete(pNode->Next);    pNode->Next = pTemp;}

Mike.


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.


Not possible.

There are hacks to mimic the deletion.

But none of then will actually delete the node the pointer is pointing to.

The popular solution of deleting the following node and copying its contents to the actual node to be deleted has side-effects if you have external pointers pointing to nodes in the list, in which case an external pointer pointing to the following node will become dangling.