描述
Given the head of a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Return the linked list sorted as well.

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

Input: head = [1,1,1,2,3]
Output: [2,3]
/**
* 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 == nullptr || head->next == nullptr)
return head;
ListNode ans(0);
ListNode *first = &ans;
ans.next = head;
ListNode *prev = first->next;
ListNode *cur = prev->next;
if(prev->val == cur->val && cur->next == nullptr)
return nullptr;
while(cur){
bool del = false;
while(cur->val == prev->val && cur->next !=nullptr){
prev = cur;
cur = cur->next;
del = true;
}
if(prev->val == cur->val && cur->next == nullptr){
// delete cur;
// delete prev;
first->next = nullptr;
return ans.next;
}
if(del){
first->next = cur;
prev = cur;
cur = cur->next;
}
else {
first = first->next;
prev = cur;
cur = cur->next;
}
}
return ans.next;
}
};
该博客讨论了如何删除已排序链表中所有重复的节点,只保留原始列表中的唯一数字。提供了一个C++解决方案,该解决方案首先创建一个新的虚拟头节点,然后遍历链表,删除所有连续重复的节点,最后返回新链表的头节点。示例输入和输出展示了不同情况下的链表处理结果。
700

被折叠的 条评论
为什么被折叠?



