给定一个已排序的链表的头 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) {
//不重复的节点一定是,跟pre和next的值都不相同的节点
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;
}
//创建虚拟的起始节点,cur->next=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;
//一直找到与cur->next节点不重复的节点
while(node->next && node->val == node->next->val) {
node = node->next;
}
if(cur->next == head) {
//如果head节点也是重复节点,需要指向第一个不重复的节点
head = node->next;
}
//删除这些重复的节点
cur->next = node->next;
} else {
cur = cur->next;
}
}
return head;
}
}