Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *deleteDuplicates(ListNode *head) {
if (head == NULL || head->next == NULL) {
return head;
}
ListNode dummy(-1);
auto prev = &dummy;
auto cur = head;
while (cur) {
bool dup = false;
while (cur->next != NULL && cur->val == cur->next->val) {
dup = true;
auto tmp = cur->next;
cur->next = cur->next->next;
delete tmp;
}
if (dup) {
auto tmp = cur;
cur = cur->next;
delete tmp;
continue;
}
prev->next = cur;
prev = prev->next;
cur = cur->next;
}
prev->next = cur;
return dummy.next;
}
};
本文介绍如何在保持链表排序的情况下,移除所有重复的节点,仅保留唯一的数值。通过实例演示了如何实现这一功能,涉及链表操作及算法优化。
724

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



