# 删除排序链表中的重复元素 II

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除链表中所有存在数字重复情况的节点,只保留原始链表中 没有重复出现 的数字。

返回同样按升序排列的结果链表。

 

示例 1:

输入:head = [1,2,3,3,4,4,5]
输出:
[1,2,5]

示例 2:

输入:head = [1,1,1,2,3]
输出:
[2,3]

 

提示:

以下程序实现了这一功能,请你填补空白处内容: ```cpp #include #include struct ListNode { int val; struct ListNode *next; }; struct ListNode *deleteDuplicates(struct ListNode *head) { struct ListNode dummy; struct ListNode *p, *q, *prev; prev = &dummy; dummy.next = head; p = q = head; while (p != NULL) { _____________________ } return dummy.next; } int main(int argc, char **argv) { int i; struct ListNode *head = NULL; struct ListNode *prev = NULL; struct ListNode *p; for (i = 0; i < argc - 1; i++) { p = malloc(sizeof(*p)); p->val = atoi(argv[i + 1]); p->next = NULL; if (head == NULL) { head = p; prev = head; } else { prev->next = p; prev = p; } } p = deleteDuplicates(head); while (p != NULL) { printf("%d ", p->val); p = p->next; } printf("\n"); return 0; } ``` ## template ```cpp #include #include struct ListNode { int val; struct ListNode *next; }; struct ListNode *deleteDuplicates(struct ListNode *head) { struct ListNode dummy; struct ListNode *p, *q, *prev; prev = &dummy; dummy.next = head; p = q = head; while (p != NULL) { while (q != NULL && q->val == p->val) { q = q->next; } if (p->next == q) { prev = p; } else { prev->next = q; } p = q; } return dummy.next; } int main(int argc, char **argv) { int i; struct ListNode *head = NULL; struct ListNode *prev = NULL; struct ListNode *p; for (i = 0; i < argc - 1; i++) { p = malloc(sizeof(*p)); p->val = atoi(argv[i + 1]); p->next = NULL; if (head == NULL) { head = p; prev = head; } else { prev->next = p; prev = p; } } p = deleteDuplicates(head); while (p != NULL) { printf("%d ", p->val); p = p->next; } printf("\n"); return 0; } ``` ## 答案 ```cpp while (q != NULL && q->val == p->val) { q = q->next; } if (p->next == q) { prev = p; } else { prev->next = q; } p = q; ``` ## 选项 ### A ```cpp while (q != NULL && q->val == p->val) { q = q->next; } if (p->next == q) { prev = p; } else { prev->next = q; } ``` ### B ```cpp while (q != NULL && q->val == p->val) { q = q->next; } if (p->next == q) { prev = p; } p = q; ``` ### C ```cpp while (q != NULL && q->val == p->val) { q = q->next; } if (p->next == q) { prev->next = q; } p = q; ```