Leetcode 237. Delete Node in a Linked List
You are given the head
of a linked list and a node that needs to be deleted. You are provided access only to that node. The linked list node structure is defined as follows:
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
Write a function to delete the given node from the linked list.
Note that you should not return the head
of the linked list; instead, you should mutate the given node’s value and pointers directly.
Given only access to the node to be deleted:
This way, the current node effectively takes the place of the next node, thereby “deleting” itself.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
void deleteNode(ListNode* node) {
// Ensure the node and its next are not null (although guaranteed by constraint)
if (node == nullptr || node->next == nullptr) {
return;
}
// Copy the data from the next node to the current node
node->val = node->next->val;
// Remove the next node by adjusting the pointers
ListNode* nodeToDelete = node->next;
node->next = node->next->next;
// Optional but good practice: Explicit deallocation (uncomment if using a custom allocator)
// delete nodeToDelete;
}
};
The time complexity of the above solution is (O(1)) because we are just copying values and updating pointers in constant time.
The space complexity is also (O(1)) since we are not using any additional space that scales with the input.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?