The beauty of programming: deleting a node from a single-chain table without headers.
1. Problem Description
Suppose there is a single-chain table without a header pointer. A pointer points to a node (not the first or the last) in the middle of the single-chain table. Delete the node from the single-chain table.
As shown in:
In this case, we all know that we can copy data and next of the next node to the current node, set next of the current node to the next node, and then release the memory occupied by the next node (free ),
If the red text condition is removed:
There is a problem with the above method. Generally, the code of the above method is as follows:
void DeleteRandomNode(Node* pCurrent){ if(pCurrent == NULL) return; Node* pNext = pCurrent->next;
if(pNext == NULL)
{
// Indicates that the current node is the last Node
PCurrent = NULL; // if this is the last node, the current pointer is set to NULL. These statements are incorrect!
} pCurrent->data = pNext->data; pCurrent->next = pNext->next; delete pNext; }
The red comment illustrates the problem: Setting pCurrent to NULL does not change the next value of the previous Node of the current Node, because the next value of the previous Node stores the Node address pointed to by pCurrent.
Simply put, pCurrent only saves a memory address, and sets pCurrent to NULL without changing the next value of the previous node. If the current node is the last node, the next value of the previous node should be NULL, but obviously the above method cannot meet this requirement. Therefore, the problem cannot be solved through the above method after the red-letter condition is removed.
Ah