题目描述 [删除链表中重复的结点]
在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
解题思路
- 新建一个头节点解决头节点就重复问题
- 三指针去除重复链表,pre, pHead,pHead->next
1.遍历链表,如果当前节点和下个节点得值相等,则继续遍历一直到找到不重复得节点为止,并且将pre->next指向pHead- 如果不等,则不重复,pre=pHead, pHead =pHead->next
代码
class Solution {
public:
ListNode* deleteDuplication(ListNode* pHead)
{
if(!pHead || !pHead->next) return pHead;
ListNode *pre = new ListNode(0);
pre->next = pHead;
ListNode *preHead = pre;
while(pHead && pHead->next){
if(pHead->val==pHead->next->val){
int val = pHead->val;
while(pHead && pHead->val==val)
pHead = pHead->next;
pre->next = pHead;
}else{
pre = pHead;
pHead = pHead->next;
}
}
return preHead->next;
}
};