Leetcode 203. Remove Linked List Elements
Given the head of a linked list and a value val
, remove all the nodes of the linked list that have Node.val == val
, and return the new head.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
nullptr
.nullptr
initially?
nullptr
, which represents an empty list.prev
) to keep track of the last node that is not removed, and another (curr
) to traverse the list.curr->val == val
, adjust prev->next
to skip over the current node.prev
pointer to the current node.dummy->next
, which is the new head of the modified list.#include <iostream>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode* removeElements(ListNode* head, int val) {
ListNode* dummy = new ListNode(-1);
dummy->next = head;
ListNode* prev = dummy;
ListNode* curr = head;
while (curr != nullptr) {
if (curr->val == val) {
prev->next = curr->next;
} else {
prev = curr;
}
curr = curr->next;
}
ListNode* newHead = dummy->next;
delete dummy; // Free memory allocated for dummy node
return newHead;
}
};
// Function to print the list for testing purposes
void printList(ListNode* head) {
while (head != nullptr) {
std::cout << head->val << " -> ";
head = head->next;
}
std::cout << "nullptr" << std::endl;
}
// Main function for simple testing
int main() {
Solution solution;
// Create a sample list 1->2->6->3->4->5->6
ListNode* list = new ListNode(1, new ListNode(2, new ListNode(6, new ListNode(3, new ListNode(4, new ListNode(5, new ListNode(6)))))));
// Print original list
std::cout << "Original List: ";
printList(list);
// Remove all nodes with value 6
ListNode* modifiedList = solution.removeElements(list, 6);
// Print modified list
std::cout << "Modified List: ";
printList(modifiedList);
// Clean up memory
while (modifiedList != nullptr) {
ListNode* tmp = modifiedList;
modifiedList = modifiedList->next;
delete tmp;
}
return 0;
}
The time complexity is O(n), where n
is the number of nodes in the linked list. This is because we traverse each node exactly once. The space complexity is O(1), as we are using only a few extra pointers regardless of the list’s size.
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?