题目:
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
Example 1:
Input: 1->2->3->3->4->4->5 Output: 1->2->5
Example 2:
Input: 1->1->1->2->3 Output: 2->3
代码:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* delDuplicate(ListNode* p) {
while (p) {
if (!p->next || p->val == p->next->val) {
p = p->next;
}
else { p = p->next; break; }
}
return p;
}
ListNode* deleteDuplicates(ListNode* head) {
if (!head)return head;
ListNode* first = new ListNode(0);
ListNode* p = first;
while (head) {
while (head->next&&head->val == head->next->val) {
head = delDuplicate(head);
if (!head)break;
}
p->next = head;
if (!head)continue;
p = p->next;
head = head->next;
}
return first->next;
}
};
想法:
考虑head为NULL的情况