Lets remove all duplicate elements from a sorted singly linked list.

For example,

Suppose given linked list contains following elements in given order,

1, 2, 3, 4, 4, 5, 6, 7, 7, 7, 7, 9, 89

After doing this operation on given linked list result should be,

1, 2, 3, 4, 5, 6, 7, 9, 89

Solution:

As list is already sorted therefore all the all similar elements will be together i.e. if element with value 2 is repeated then all instance of elements with value 2 will be together i.e.

1,2,2,2,2,5,6,8

Therefore, we just need to check if there is more than 2 adjacent nodes with same contents or not.
If yes then delete that node and move forward.


Algo Used:

Traverse the whole linked list and always keep track of last visited Node.
During traversal while visiting each node check it contents match with last node’s content
If Data matches
——->Then delete the current node and go to next node
If Data dont matches
——->Then just update the last visited node pointer by making it to point to current node
——->Then go the next node.

Code for the function is as follows,

complete Code is as follows,

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.