Challenge: Remove Element from Generic Linked List

Test your knowledge by solving this coding challenge.

Problem statement

The input consists of a generic linked list and an element to remove if it’s inside the list.

For the following input:

[1, 2, 3, 4, 5]
3

The output should be:

[1, 2, 4, 5]

For the following input:

["Hello", "World"]
"Hello"

The output should be:

["World"]

You should perform the removal in place by changing the pointers without constructing another list.

An element may appear multiple times in the list, in no particular order.

Challenge

Complete the functions in the following code widget using local references. The definition of the list structure is present in the background.

Note: We stress again that It’s crucial to make a memory drawing to be able to solve problems with linked lists. It’s hard to figure out how to set the pointers without visualizing them on paper beforehand.

Since the linked list is generic, the removeElement function will do the following:

  • Accept a comparator function that can compare two elements and return 1 when they are equal.
  • Accept a free function to deallocate the node.
  • Accept the node value that needs to be removed as void* because the function must be generic.

We already provide the typedef of the comparator and free functions.

Your task is to implement the functions marked with TODO: compareInteger, compareString, and removeElement.

The test cases will call your removeElement function to remove elements from a list of integers and a list of strings. Don’t hardcode anything inside removeElement regarding the concrete type of the elements. The implementation must be fully generic.

The test cases will only use the appropriate helper functions. For example, for strings, the test cases will always use compareString.

Get hands-on with 1400+ tech skills courses.