I have the following code (correct for my simple tests) for a linked list for no duplicates, but I think it is a bit ugly.
Could anyone recommend a cleaner way to handle the duplicate code? The current piece in question is:
if( (val == cur->val) || (cur->next && (val == cur->next->val)) )
But I think that a better solution might exist (that I don't see) using a different use of comparison operators.
Also, can someone give me a suggestion for a "useful" assert or to inside here. It is hard to tell when to assert, especially if you have an if statement doing it for you.
struct Node
{
Node(int v):val(v),next(NULL){}
int val;
Node * next;
};
void insert(Node ** ppHead, const int val)
{
if(ppHead == NULL)
return;
if(*ppHead == NULL || val < (*ppHead)->val)
{
Node * tmp = new Node(val); // new throws
tmp->next = *ppHead;
*ppHead = tmp;
}
else
{
Node * cur = *ppHead;
while(cur->next && (val > cur->next->val))
cur = cur->next;
if( (val == cur->val) || (cur->next && (val == cur->next->val)) )
return;
Node * tmp = new Node(val); // new throws
tmp->next = cur->next;
cur->next = tmp;
}
return;
}
int _tmain(int argc, _TCHAR* argv[])
{
Node * list = NULL;
int x[] = { 5, 4, 6, 7, 1, 8, 1, 8, 7, 2, 3, 0, 1, 0, 4, 9, 9 };
int size = sizeof(x) / sizeof(x[0]);
for(int i = 0; i < size; i++)
insert(&list, x[i]);
Node * cur = list;
while(cur) {
printf (" %d", cur->val);
cur = cur->next;
}
printf("\n");
return 0;
}