您的位置:首页 > 其它

删除单链表中重复的元素

2012-10-09 22:29 323 查看
用Hashtable辅助,遍历一遍单链表就能搞定。
/article/4670721.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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: