---
# System prepended metadata

title: Question 83. Remove Duplicates from Sorted List
tags: [leetcode]

---

###### tags: `leetcode`
# Question 83. Remove Duplicates from Sorted List
### Description:
Given the head of a sorted linked list, delete all duplicates such that each element appears only once. Return the linked list sorted as well.
### Solution:
remove until no duplication.
***Remember to delete the unused node to avoid memory leak!!!(Line 21 and Line 25)***
### AC code
```cpp=
/**
 * Definition for singly-linked list.
 * 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:
    ListNode* deleteDuplicates(ListNode* head) {
        ListNode* cur = head;
        ListNode* tmp;
        while(cur!=NULL){
            while((cur->next!=NULL) && (cur->val == cur->next->val)){
                if(cur->next->next!=NULL){
                    tmp = cur->next;
                    cur->next = cur->next->next;
                    delete tmp;
                }
                else{
                    if(cur->next)
                        delete cur->next;
                    cur->next = NULL;
                }
            }
            cur = cur->next;
        }
        return head;
    }
};
```