We’ve had a couple of fairly easy Leetcode July Challenge problems in a row this week, so I decided to do a little catch up and post for two problems today. If I keep this schedule, problem discussions will be posted on the same day as its challenge for the rest of the month.

Today’s challenge is one of those basic problems. We’re given a singly linked list and an argument value and asked to remove all nodes from the linked list whose val property is equal to the argument value. This is just a matter of stepping through the list and removing the nodes. The one design consideration is how to handle the case where the head needs to be removed, which can be handled either as a special case or by using a dummy head node so the entire list can be treated as the general case; I use the latter approach. Probably not necessary, but I like to show a sample case.

Input List: 3->2->3->4->5

Remove value: 3

Output List: 2->4->5

So, here’s the code as described above. One small thing to note when using the dummy head node algorithm, as I do, is that it’s important to remember delete that extra node at the end of the algorithm to prevent a memory leak.

ListNode* removeElements(ListNode* head, int val) {
   ListNode* dummy = new ListNode(0, head);
   ListNode* prev = dummy;
   ListNode* current = head;
   while(current) {
	  if(current->val == val) {
		 prev->next = current->next;
		 ListNode* temp = current;
		 current = current->next;
		 delete temp;
	  }
	  else {
		 prev = current;
		 current = current->next;
	  }
   }
   head = dummy->next;
   delete dummy;
   return head;
}