203. Remove Linked List Elements
Remove Linked List Elements
Given the head
of a linked list and an integer val
, remove all the nodes of the linked list that has Node.val == val
, and return the new head.
Example 1:
Input: head = [1,2,6,3,4,5,6], val = 6 Output: [1,2,3,4,5]
Example 2:
Input: head = [], val = 1 Output: []
Example 3:
Input: head = [7,7,7,7], val = 7 Output: []
Constraints:
- The number of nodes in the list is in the range
[0, 104]
. 1 <= Node.val <= 50
0 <= val <= 50
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @param {number} val
* @return {ListNode}
*/
var removeElements = function(head, val) {
if (head === null) {
return head;
}
let currentNode = head;
let previousNode;
while(currentNode != null){
if(currentNode.val == val){
if(currentNode == head){
currentNode = head.next;
head.next = null;
head = currentNode;
continue;
}else{
previousNode.next = currentNode.next;
currentNode.next = null;
currentNode = previousNode.next;
continue;
}
}
previousNode = currentNode;
currentNode = currentNode.next;
}
return head;
};
Time Complexity
We traverse the Linked list from left to right only once, hence the time complexity will be O(n).
Space Complexity
We are using two extra linked list space for currentNode and previousNode hence the space complexity will be O(n)
Conclusion
That’s all folks! In this post, we solved LeetCode problem #203. Remove Linked List Elements
I hope you have enjoyed this post. Feel free to share your thoughts on this.
You can find the complete source code on my GitHub repository. If you like what you learn. feel free to fork 🔪 and star ⭐ it.
In this blog, I have tried to solve leetcode questions & present the most important points to consider when improving Data structure and logic, feel free to add, edit, comment, or ask. For more information please reach me here
Happy coding!
Comments
Post a Comment