# Remove Duplicates from Sorted List in C++

Suppose we have a sorted linked list; we have to delete all duplicates such that each element appears only once.

So, if the input is like [1,1,2,3,3,3,4,5,5], then the output will be [1,2,3,4,5]

To solve this, we will follow these steps −

• dummy := make a new node with value -inf

• next of dummy := head

• curr = dummy

• while curr is non-zero, do −

• next = next of curr

• while (next is not null and val of next is same as val of curr), do −

• next := next of next

• next of curr := next

• curr := next

• return next of dummy

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode*dummy = new ListNode(INT_MIN);
ListNode * curr = dummy;
while(curr){
ListNode * next = curr->next;
while(next && next->val==curr->val)
next = next->next;
curr->next = next;
curr=next;
}
return dummy->next;
}
};
main(){
Solution ob;
vector<int> v = {1,1,2,3,3,3,4,5,5};
}
{1,1,2,3,3,3,4,5,5}
[1, 2, 3, 4, 5, ]