Given a linked list sorted in increasing order, write a function that removes duplicate nodes from it by traversing the list only once.

For example, the list {1, 2, 2, 2, 3, 4, 4, 5} should be converted into the list {1, 2, 3, 4, 5}.

Practice this problem

Since the list is sorted, we can proceed down the list and compare adjacent nodes. When adjacent nodes are the same, remove the second one. There’s a tricky case where the node after the next node needs to be noted before the deletion.

The algorithm can be implemented as follows in C, Java, and Python:

C


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> NULL

Java


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> null

Python


Download  Run Code

Output:

1 —> 2 —> 3 —> 4 —> 5 —> None

The time complexity of the above solution is O(n), where n is the total number of nodes in the linked list, and doesn’t require any extra space.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf