83. Remove Duplicates from Sorted List

时间:2022-12-13 07:35:41

1. 问题描述

Given a sorted linked list, delete all duplicates such that each element appear only once.
For example,
Given 1->1->2, return 1->2.
Given 1->1->2->3->3, return 1->2->3.
Tags: Linked List

2. 解题思路
3. 代码

class Solution {
public:
    ListNode* deleteDuplicates(ListNode* head)
    {
        if (NULL == head)
        {
            return head;
        }
        set<int> tSet;

        ListNode *pTemp;
        pTemp = head;
        while (NULL != pTemp)
        {
            tSet.insert(pTemp->val);
            while (NULL != pTemp->next)
            {
                if (tSet.count(pTemp->next->val) > 0)
                {
                    ListNode *p = pTemp->next;
                    pTemp->next = p->next;
                }
                else
                {
                    break;
                }
            }
            pTemp = pTemp->next;
        }
        return head;
    }
};

4. 反思