/*
Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list.
For example,
Given 1->2->3->3->4->4->5, return 1->2->5.
Given 1->1->1->2->3, return 2->3.
*/
#include <set>
#include <string>
#include <iostream>
using namespace std;
//Time O(nlongn), space O(n)
struct node{
int val;
node *next;
node(int v = 0): val(v), next(NULL){};
};
class Solution{
public:
node* RemoveDuplicates(node* n){
set<int> dup;
set<int> count;
node *guard = new node(-1);
guard->next = n;
while (NULL != n){//n
if (count.find(n->val) != count.end()){//logn
dup.insert(n->val);
}
else{
count.insert(n->val);
}
n = n->next;
}
n = guard->next;
node *prev = guard;
while (NULL != n){
if (dup.find(n->val) != dup.end()){
prev->next = n->next;//delete
delete n;
n = prev->next;
}
else{
prev = n;
n = n->next;
}
}
node * re = guard->next;
delete guard;
return re;
}
};
void PrintLinkedList(node *root){
if (NULL == root) return;
while (NULL != root->next){
cout << root->val << "->";
root = root->next;
}
cout << root->val << endl;
}
node * LinkedList(int *a, int l){
if (0 == l || NULL == a) return NULL;
node *root = new node(a[0]);
node *prev = root;
for (int i = 1; i < l; ++i){
node *n = new node(a[i]);
prev->next = n;
prev = n;
}
return root;
}
void DeleteLinkedList(node *root){
if (NULL == root) return;
node *next = NULL;
while (NULL != root){
next = root->next;
delete root;
root = next;
}
}
int main(){
Solution sol;
int a1[] = {1,2,3,4,5,6};
node * root1 = LinkedList(a1, sizeof(a1)/sizeof(int));
int a2[] = {1,2,1,4,4,6};
node * root2 = LinkedList(a2, sizeof(a2)/sizeof(int));
int a3[] = {3,4,1,4,4,1};
node * root3 = LinkedList(a3, sizeof(a3)/sizeof(int));
PrintLinkedList(root1);
root1 = sol.RemoveDuplicates(root1);
PrintLinkedList(root1);
PrintLinkedList(root2);
root2 = sol.RemoveDuplicates(root2);
PrintLinkedList(root2);
PrintLinkedList(root3);
root3 = sol.RemoveDuplicates(root3);
PrintLinkedList(root3);
DeleteLinkedList(root3);
DeleteLinkedList(root2);
DeleteLinkedList(root1);
}
answered
01 Apr, 06:32
FH86
21●3
accept rate:
0%