Removing duplicates from a linked list is a popular interview question. Although its simple, some people may ask the implement the linked list as such along with this. Yes, you need to add items to the linked list, remove an item from the linked list to do the removeDuplicates function.
Move step-by-step. (The questions to ask before you start)
- Is the linked list sorted?
- How large is the linked list? Is the size of the linked list fixed?
The above questions are because of the following reasons,
- sorted list means duplicates are found in single iteration. (just a single scan and remove)
- huge list means – doing a easy sorting would help. Dynamic list means – no sorting, need to try other approaches like heap. If space allowed, you can use hash map
Always go with the brute force way. 2 for loop approach.
Things found while writing code:
- this pointer is const!! :) which means List *const this; u cannot change what it points to. But u can change the object inside it. const member function has it like, List const *const this;
- As we delete node using next pointers in the list, to free the pointer you should take a backup of the pointer.
- Base test cases must be run to catch errors: 2 nodes, 1 node, first node, last node.
- Reference to a pointer will help in modifying the pointer in a function.
- The above code is a O(n2) complexity. Brute force. Best way is to do merge sort. – O(n log n) and when doing the merge, remove duplicates.