自己无脑AC的代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeDuplicateNodes(ListNode* head) {
        unordered_set<int> hash_set;
        ListNode * p = head,*loc = head,*last = head;
        while(p)
        {
            if(!hash_set.count(p->val))
            {
                hash_set.insert(p->val);
                loc->val = p->val;
                last = loc;
                loc = loc->next;
            }

            p = p ->next;
        }
        if(last) last->next = NULL;

        return head;
    }
};

讨论区更精炼的代码,更精炼,更好理解:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* removeDuplicateNodes(ListNode* head) {
        unordered_set<int> set;
        ListNode * cur = head;

        while(cur&&cur->next){
            set.insert(cur->val);
            //如果下一个元素在集合中,跳过下一个元素
            if(set.count(cur->next->val)) cur->next = cur->next->next;
            else cur = cur->next;
        }
        return head;
    }
};