Files
dsa-competitive-programming/leetcode/lc237.cpp
T

12 lines
902 B
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 nodes 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.