# Leetcode 82. Delete duplicate elements in the sorting linked list II

2022-04-29 14:03:57

## 82、 Delete duplicate elements from the sort list II

1） Title Description

Given the header of a sorted linked list `head` , Delete all nodes with duplicate numbers in the original linked list , Leave only different numbers . return Sorted linked list .

Example 1：

`````` Input ：head = [1,2,3,3,4,4,5]
Output ：[1,2,5]
``````

Example 2：

`````` Input ：head = [1,1,1,2,3]
Output ：[2,3]
``````

Tips ：

• The number of nodes in the linked list is in the range `[0, 300]` Inside
• `-100 <= Node.val <= 100`
• The title data ensures that the linked list has been in ascending order array

2） analysis

• Set a front node , Its `next` Pointer to `head`;
• from `head` Start traversing the linked list , If the value of the current node is equal to the value of the next node , Then record the value of the current node , And delete from the current node , Until the value of the next node is not the value of the current node or the next node is empty ;
• If the value of the current node is not equal to the value of the next node , Indicates that the current node has only one value , Traverse the next node .

3）`C++` Code

``````/** * 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* curr=pre;

while(curr->next&&curr->next->next){

if(curr->next->val==curr->next->next->val){

int temp=curr->next->val;
while(curr->next&&curr->next->val==temp){

ListNode* tempNode=curr->next;
curr->next=curr->next->next;
delete(tempNode);
}
}
else
curr=curr->next;
}
return pre->next;
}
};
``````