题目
给定一个排序链表,删除所有含有重复数字的节点,只保留原始链表中 没有重复出现 的数字。
示例 1:
输入: 1->2->3->3->4->4->5
输出: 1->2->5
示例 2:
解析
代码
/**
* 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) {
ListNode* dummy = new ListNode(0);
dummy->next = head;
ListNode* pre = dummy;
ListNode* cur = pre->next;
while (cur) {
int num = 0;
ListNode* p = cur;
while (p && p->val == cur->val) {
++num;
p = p->next;
}
if (num > 1) {
pre->next = p;
} else {
pre = cur;
}
cur = p;
}
ListNode* retNode = dummy->next;
delete dummy;
return retNode;
}
};