Remove Duplicates from Sorted List II
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given
Given
*/For example,
Given
1->2->3->3->4->4->5, return 1->2->5.Given
1->1->1->2->3, return 2->3. /**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
map<int,int> hashMap;
if(head==NULL) return head;
ListNode *curr = head;
ListNode *prep;
while(curr!=NULL){
if(hashMap.find(curr->val)==hashMap.end()){
hashMap[curr->val]=1;
} else hashMap[curr->val] = hashMap[curr->val]+1;
curr = curr->next;
}
while(head!=NULL && hashMap[head->val]>1){
head = head->next;
}
if (head==NULL) return head;
prep = head;
curr = head->next;
while(curr!=NULL){
if(hashMap[curr->val]==1){
prep = curr;
curr = curr->next;
} else {
curr = curr->next;
prep->next = curr;
}
}
return head;
}
};
No comments:
Post a Comment