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

<p>存在一个按升序排列的链表，给你这个链表的头节点 <code>head</code> ，请你删除所有重复的元素，使每个元素 <strong>只出现一次</strong> 。</p><p>返回同样按升序排列的结果链表。</p><p><strong>示例 1：</strong></p><img alt="" src="https://img-blog.csdnimg.cn/img_convert/b6eba8ba59536dfb80d2f593a68a3f5f.png#pic_center" /><pre><strong>输入：</strong>head = [1,1,2]<strong><br />输出：</strong>[1,2]</pre><p><strong>示例 2：</strong></p><img alt="" src="https://img-blog.csdnimg.cn/img_convert/0141f292aa8d31b92eab3049dc01b485.png#pic_center" /><pre><strong>输入：</strong>head = [1,1,2,3,3]<strong><br />输出：</strong>[1,2,3]</pre><p><strong>提示：</strong></p><ul>	<li>链表中节点数目在范围 <code>[0, 300]</code> 内</li>	<li><code>-100 <= Node.val <= 100</code></li>	<li>题目数据保证链表已经按升序排列</li></ul>
<p>以下<span style="color:red">错误</span>的选项是？</p>

## aop

### before

```c
#include <bits/stdc++.h>
using namespace std;

struct ListNode
{
    int val;
    ListNode *next;
    ListNode(int x) : val(x), next(NULL) {}
};
```

### after

```c

```

## 答案

```c
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

```c
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

```c
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

```c
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;
    }
};
```
