Given a sorted linked list, delete all duplicates such that each element appear only once.
Example 1:
Input: 1->1->2 Output: 1->2
Example 2:
Input: 1->1->2->3->3 Output: 1->2->3
方法1:利用set,count()查找当前元素的个数,存在删除,不存在添加。使用两个指针记录前一个和当前节点。
/**
* 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> nodeValue;
ListNode *pre=head, *cur=head;
if(head==NULL) return head;
cur=pre->next;
nodeValue.insert(head->val);
while(cur!=NULL){
if(nodeValue.count(cur->val)==1){
pre->next=cur->next;
}else{
nodeValue.insert(cur->val);
pre=cur;
}
cur=cur->next;
}
return head;
}
};
tips:指针使用->访问元素,定义 nodeList *pre, *cur;