在一个排序的链表中,存在重复的结点,请删除该链表中重复的结点,重复的结点不保留,返回链表头指针。 例如,链表1->2->3->3->4->4->5 处理后为 1->2->5
/*
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 * p=new ListNode(-1);
p->next=pHead;
ListNode *p1=p;
ListNode *p2=p->next;
while(p2)
{
//找到不相等的位置
while(p2->next!=NULL&&p2->val==p2->next->val)
p2=p2->next;
//如果位置不在下一个,则连接。
if(p1->next!=p2)
{
p2=p2->next;
p1->next=p2;
}
//头结点是空的
else
{
p1=p2;
p2=p2->next;
}
}
return p->next;
}
};