存在一个按升序排列的链表,给你这个链表的头节点 head
,请你删除所有重复的元素,使每个元素 只出现一次 。
返回同样按升序排列的结果链表。
示例 1:
输入:head = [1,1,2]
输出:[1,2]
示例 2:
输入:head = [1,1,2,3,3]
输出:[1,2,3]
提示:
- 链表中节点数目在范围
[0, 300]
内 -100 <= Node.val <= 100
- 题目数据保证链表已经按升序排列
解答
与82. 删除排序链表中的重复元素 II的区别在于不要求把重复的节点都删完:
/**
* 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) {
if(!head || !head->next)
return head;
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = head;
bool flag = false;
while(cur){
ListNode* next = cur->next;
int cur_val = cur->val;
while(cur->next && cur->next->val == cur_val){
next = cur->next;
delete cur;
cur = next;
flag = true;
}
if(flag){
pre->next = cur;
cur = cur->next;
pre = pre->next;
}
else{
pre = cur;
cur = next;
}
}
return dummy->next;
}
};
精简下代码:
class Solution {
public:
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next)
return head;
ListNode* node = head;
while(node && node->next){
if(node->val == node->next->val){
ListNode* deleted_node = node->next;
node->next = node->next->next;
delete deleted_node;
}
else{
node = node->next;
}
}
return head;
}
};