删除链表中的重复节点(不保留重复节点)
(剑指offer上面对这个题难度是4(总共五颗星),我寻思着,是我最近进步了?我觉得没那么难吧)
说下我的思路:利用map存储链表节点的值和次数,遍历map,当map元素次数为1的时候,开辟一个新结点,将次数为1的值存储起来,挂到新链表中,最后返回新链表的头。
这里要注意的是为了防止第一个和第二个就是重复节点,例如{1,1},我们在构造新链表的时候,最好加一个头部。
代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
*/
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(pHead==NULL||pHead->next==NULL)
return pHead;
ListNode* res=new ListNode(0);
ListNode* tail=res;
map<int,int> m;
ListNode* cur=pHead;
while(cur)
{
m[cur->val]++;
cur=cur->next;
}
map<int,int>::iterator it;
for(it=m.begin();it!=m.end();it++)
{
if(it->second==1)
{
ListNode* newnode=(ListNode*)malloc(sizeof(ListNode));
newnode->val=it->first;
newnode->next=NULL;
tail->next=newnode;
tail=newnode;
}
}
return res->next;
}
};
当然如果要删除表中的重复节点,只保留一个重复节点,那直接用set好了,把链表的数据都放入set中,排序+去重,在构建新链表,把这些节点都挂起来,和上述方法是一样的。