天天看點

C++之删除連結清單的重複元素

輸入:[1, 2, 3, 3, 2, 1]
輸出:[1, 2, 3]

示例2:
輸入:[1, 1, 1, 1, 2]
輸出:[1, 2]      
/**
 * 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) {
        set<int> s;
        ListNode* cur=head;
        while(cur&&cur->next)
        {
            s.insert(cur->val);
            //如果此節點重複,則跨過cur->next
            if(s.count(cur->next->val)) cur->next=cur->next->next;
            else
                cur=cur->next;
        }
        return head;
    }
};      

繼續閱讀