用Hashtable辅助,遍历一遍单链表就能搞定。
http://www.cnblogs.com/Jax/archive/2009/12/11/1621504.html
实践中发现,curr从表头开始,每次判断下一个元素curr.Next是否重复,如果重复直接使用curr.Next = curr.Next.Next; 就可以删除重复元素。
#include <afxtempl.h>// CMap
// remove duplicated elements from the list
node* RemoveDup(node* head)
{
CMap<int, int, node*, node*> ht;// a Hashtable to store values
if ( head != NULL )
{
node* p = head;
ht[p->data] = p;// put the first value into the table
while( p->next )
{
if ( ht[p->next->data] )// p->next has a dup value
{
node* tmp = p->next;
p->next = p->next->next;
delete tmp;// remove the dup, but p does not move forward
}
else
{
ht[p->next->data] = p->next;// store the p->next value
p = p->next;// p moves forward
}
}
}
return head;
}