Deleting a middle node from a single linked list when pointer to the previous node is not available
Solution 1:
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).
- 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) -> ...
- Copy the NEXT of second Node(i+1) into a temporary variable.
- 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.
Solution 2:
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.