# Leetcode Remove Duplicates from Sorted List II problem solution In the Leetcode Remove Duplicates from Sorted List II problem solution Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

Example 1:

Output: [1,2,5]

Example 2:

Output: [2,3]

Constraints:

• The number of nodes in the list is in the range [0, 300].
• -100 <= Node.val <= 100
• The list is guaranteed to be sorted in ascending order.

## Solution in C Programming

``````/**
* struct ListNode {
*     int val;
*     struct ListNode *next;
* };
*/
{
struct ListNode* before_head = malloc(sizeof(struct ListNode));
while(p2!=NULL)
{
bool should_del = false;
while(p2->next!=NULL && p2->val == p2->next->val)
{
should_del = true;
p2 = p2->next;
}
if(should_del)
p1->next = p2->next;
else
p1 = p1->next;

p2 = p1->next;
}

}``````

## Solution in C++ Programming

``````/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode() : val(0), next(nullptr) {}
*     ListNode(int x) : val(x), next(nullptr) {}
*     ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
while(run && run->val == head->val) run = run->next;
}
};``````

## Solution in Java Programming

``````class Solution {
ListNode p1 = new ListNode(-1);
ListNode cur = p1;
}
} else {
cur = cur.next;
cur.next = null;
}
}
return p1.next;
}
}``````

## Solution in Python Programming

``````class Solution(object):
"""
:rtype: ListNode
"""
memo = collections.defaultdict(int)
for key,value in memo.items():
if value > 1:
memo.pop(key)

dummy = ListNode(0)
res = dummy
for i in sorted(memo.keys()):
dummy.next = ListNode(i)
dummy = dummy.next
return res.next ``````

## Solution in C# Programming

``````/**
* public class ListNode {
*     public int val;
*     public ListNode next;
*     public ListNode(int val=0, ListNode next=null) {
*         this.val = val;
*         this.next = next;
*     }
* }
*/
public class Solution {

Dictionary<int, int> dict = new Dictionary<int, int>();
while (current != null)
{
if (dict.ContainsKey(current.val))
{
dict[current.val]++;
}
else
{
}
current = current.next;
}

foreach (var d in dict)
{
if (d.Value == 1)
{
finalCurrent.next = new ListNode(d.Key);
finalCurrent = finalCurrent.next;
}
}
}
}`````` #### By Neha Singhal

Hi, my name is Neha singhal a software engineer and coder by profession. I like to solve coding problems that give me the power to write posts for this site.