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

存在一个按升序排列的链表,给你这个链表的头节点 head ,请你删除所有重复的元素,使每个元素 只出现一次

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

 

示例 1:

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

示例 2:

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

 

提示:

以下错误的选项是?

## aop ### before ```cpp #include using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; ``` ### after ```cpp ``` ## 答案 ```cpp class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (!head || !head->next) return head; head->next = deleteDuplicates(head->next); if (head->val != head->next->val) head = head->next; return head; } }; ``` ## 选项 ### A ```cpp class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (head == NULL || head->next == NULL) return head; ListNode *p = head; ListNode *q = head->next; while (p->next != NULL) { if (p->val == q->val) { if (q->next == NULL) p->next = NULL; else { p->next = q->next; q = q->next; } } else { p = p->next; q = q->next; } } return head; } }; ``` ### B ```cpp class Solution { public: ListNode *deleteDuplicates(ListNode *head) { ListNode *cur = head; while (cur != NULL) { ListNode *rear = cur->next; if (rear == NULL) return head; if (cur->val == rear->val) cur->next = rear->next; else cur = cur->next; } return head; } }; ``` ### C ```cpp class Solution { public: ListNode *deleteDuplicates(ListNode *head) { if (head == NULL) return head; ListNode *ptr{head}; while (ptr->next != NULL) { if (ptr->val == ptr->next->val) { ListNode *p = ptr->next; ptr->next = p->next; delete p; } else { ptr = ptr->next; } } return head; } }; ```