This website collects cookies to deliver better user experience
LinkedList Questions: Delete a given node in constant time
LinkedList Questions: Delete a given node in constant time
In this series of posts, I will discuss coding questions on the LinkedList Data structure.
The posts in this series will be organized in the following way,
Question Link ❓
Possible Explanation 📝
Documented C++ Code 🧹
Time and Space Complexity Analysis ⌛🌌
The Question
Write a function to delete a node in a singly-linked list. You will not be given access to the head of the list, instead you will be given access to the node to be deleted directly.
It is guaranteed that the node to be deleted is not a tail node in the list.
💡 Give yourself atleast 5 mins to figure out the solution :)
Explanation
It is a warm-up question, there's not much to explain,
Copy the data of the next node into the given node.
#include<bits/stdc++.h>#include"../linkedlist.h"usingnamespace std;/*
-Time:O(1)
-Space:O(1)
*/classSolution{public://! given node isn't the "tail" nodevoiddeleteNode(ListNode *node){ ListNode *temp = node->next;//I can do this only because node isn't the tail node//and "node->next" will not null therefore node->val = node->next->val; node->next = node->next->next;delete temp;}};