【正确答案】
【答案解析】一个没有排序的链表,如list={a,1,x,b,e,f,f,e,a,g,h,b,m},请去掉重复项,并保留原顺序,以上链表去掉重复项后为newlist={a,1,x,b,e,f,g,h,m},请写出一个高效算法。
方法一:递归求解。
link delSame(link head)
{
link pointer,temp=head;
if(head->next==NULL)
return head;
head->next=delSame(head->next);
pointer=head->next;
while(pointer!=NULL)
{
if(head->number==pointer->number)
{
temp->next=pointer->next;
free(pointer);
pointer=temp->next;
}
else
{
pointer=pointer->next;
temp=temp->next;
}
}
return head;
}
采用递归方法效率不够高效,于是想到了方法二的Hash法。
方法二:使用Hash法,具体过程如下。
1)建立一个hash_map,key为链表中已经遍历的结点内容,开始时为空。
2)从头开始遍历链表中的结点。
①如果结点内容已经在hash_map中存在,则删除此结点,继续向后遍历。
②如果结点内容不在hash_map中,则保留此结点,将结点内容添加到hash_map中,继续向后遍历。