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* deleteDuplicates(ListNode* head) {
ListNode * p = head;
if (p == NULL || p->next == NULL) return head;
while (p->next != NULL && p->next->val == p->val) //第一个数字和第二个相同
{
while (p->next != NULL && p->next->val == p->val)
p = p->next; // 找到最后一个数字
if (p->next == NULL) return NULL; //全部数都一样
p = p->next; //找后一个数
}
ListNode * pre =p; //保存前一个
ListNode * head1 = pre;
if (p->next == NULL) return head1;
p = p->next; // 后一个 ,和第一个数字一定不同
ListNode *q;
while (p!=NULL &&p->next != NULL)
{
q = p->next;
if (p->val != q->val)
{
pre->next = p;
pre = p;
pre->next = NULL;
p = q;
}
else
{
while (q->next != NULL && q->val == q->next->val)
{
q = q->next; //最后一个相同的
}
p = q->next;
}
}
pre->next = p;
return head1;
}
};