# 【LeetCode】 83. Remove Duplicates from Sorted List ## Description > Given a sorted linked list, delete all duplicates such that each element appear only once. > 給一個排序過的linked list,刪除所有重複出現的元素,使每個元素最多只會出現一次。 ## Example: ``` Example 1: Input: 1->1->2 Output: 1->2 Example 2: Input: 1->1->2->3->3 Output: 1->2->3 ``` ## Solution * 用set記錄每個元素出現過了沒,如果出現過就刪除。 * 刪除節點要記住上一個節點。 ### Code ```C++=1 /** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: ListNode* deleteDuplicates(ListNode* head) { set<int> s; ListNode* j = NULL; for(ListNode* i = head;i!=NULL;i = i->next) { if(s.count(i->val)) { //delete j->next = i->next; } else j = i; s.insert(i->val); } return head; } }; ``` ###### tags: `LeetCode` `C++`