Remove Duplicates from Sorted List II

Description:

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.

Code:

 1   ListNode* deleteDuplicates(ListNode* head) {
 2         if (head)
 3         {
 4             ListNode* p = head;
 5             ListNode* lastNode = head;
 6             
 7             int lastDeleteVal = 0;
 8             bool flag = false;//flag为false表示还没有元素被删除
 9             
10             while (p)
11             {
12                 if ( (flag == true && p->val == lastDeleteVal)
13                 || (p->next!=NULL && p->val == p->next->val))
14                 {//删除p
15                     lastDeleteVal = p->val;
16                     if (p == head)
17                         head = p->next;
18                     else
19                         lastNode->next = p->next;
20                     p = p->next;
21                     if (flag == false)
22                         flag = true;
23                 }
24                 else
25                 {
26                     lastNode = p;
27                     p = p->next;
28                 }
29             }
30         }
31         return head;
32     }
原文地址:https://www.cnblogs.com/happygirl-zjj/p/4586209.html