SoFunction
Updated on 2025-03-10

Given the pointer of the intermediate node in the linked list, the method to delete the intermediate node

The problem is as follows
Input: Pointer to node c in linked list a->b->c->d->e
Output: No return value, but the new linked list becomes a->b->d->e
answer:
I thought about it for a long time but didn't think it out. I only realized the solution after reading the prompts. A little trick was used here. To delete the intermediate node, we do not know how to delete the previous node p of the node, so we cannot delete the node by modifying the pointer (p->next=del->next), but we know that we want to delete the next node of the node, so we change our thinking, exchange the data of the node to be deleted with the data of the next node of the node, and then delete the next node, so as to achieve our goal. However, this method cannot delete the last node, and the reason is obvious.
Copy the codeThe code is as follows:

// a tricky solution,can't delete the last one element
int delete_node(NODE* node) {
int data;
NODE *p=node->next;
node->data=p->data;
node->next=p->next;
free(p);
}