mirror of
https://github.com/Manoj-HV30/dsa-competitive-programming.git
synced 2026-05-16 19:35:22 +00:00
12 lines
902 B
C++
12 lines
902 B
C++
class Solution{
|
||
public :
|
||
void deleteNode(ListNode* node){
|
||
ListNode* nextNode = node->next;
|
||
node->val = nextNode->val;
|
||
node->next = nextNode->next;
|
||
delete nextNode;
|
||
}
|
||
}
|
||
//The idea behind this solution is that since we are not given the head pointer and therefore cannot access the previous node, we cannot delete the current node in the normal way (which would require updating prev->next). So instead of deleting the given node directly, we copy the value of its next node into it. This makes the current node effectively take on the identity of the next node. Then we adjust the current node’s next pointer to skip over the next node, thereby removing it from the list. Finally, we delete that next node to free memory. This works because the problem guarantees that the given node is not the tail, so a next node always exists.
|
||
|