. - 力扣(LeetCode)
给定一个已排序的链表的头 head
, 删除原始链表中所有重复数字的节点,只留下不同的数字 。返回 已排序的链表 。
示例 1:
输入:head = [1,2,3,3,4,4,5] 输出:[1,2,5]
示例 2:
输入:head = [1,1,1,2,3] 输出:[2,3]
提示:
- 链表中节点数目在范围
[0, 300]
内 -100 <= Node.val <= 100
- 题目数据保证链表已经按升序 排列
/**
* 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* pre = nullptr;
ListNode* cur = head;
ListNode* returned_start = nullptr;
ListNode* returned_end = nullptr;
while (cur != nullptr) {
if ((!pre || cur->val != pre->val) && (!cur->next || cur->val != cur->next->val)) {
if (!returned_start) {
returned_start = cur;
returned_end = cur;
} else {
returned_end->next = cur;
returned_end = cur;
}
}
pre = cur;
cur = cur->next;
}
returned_end->next = nullptr;
return returned_start;
}
};
class Solution {
ListNode* deleteDuplicates(ListNode* head) {
if(!head || !head->next) {
return head;
}
ListNode* cur = new ListNode(0, head);
while(cur->next && cur->next->next) {
if(cur->next->val == cur->next->next->val) {
ListNode* node = cur->next->next;
while(node->next && node->val == node->next->val) {
node = node->next;
}
if(cur->next == head) {
head = node->next;
}
cur->next = node->next;
} else {
cur = cur->next;
}
}
return head;
}
}