链接:https://www.nowcoder.com/practice/fc533c45b73a41b0b44ccba763f866ef?tpId=13&&tqId=11209&rp=1&ru=/activity/oj&qru=/ta/coding-interviews/question-ranking
以下为不考虑特殊情况下的思路:
在考虑了常规情况的条件下,我们需要考虑下面两种特殊情况,例如下面的用例:
1 1 1 2 3 4(一开始就需要删除节点)
1 2 3 4 4 4(需要删除的结点在最后)
代码实现:
ListNode* deleteDuplication(ListNode* pHead)
{
//如果头结点为空或者头结点的下一个结点为空,返回当前结点
if(pHead==NULL || pHead->next==NULL)
return pHead;
ListNode*pre=NULL;
ListNode*cur=pHead;
ListNode*next=pHead->next;
while(next)
{
//如果当前结点和下一个结点不相等,则后移
if(cur->val != next->val)
{
pre=cur;
cur=next;
next=next->next;
}
else
{
while(next&&cur->val == next->val)
{
next=next->next;
}
//当一开始结点就相同,此时pre为空
if(pre)
{
pre->next=next;
}
else
{
//此时,因为要返回头结点,而前面的结点要被删除,则由pHead直接指向next结点
pHead=next;
}
//释放结点
while(cur!=next)
{
ListNode*del = cur;
cur=cur->next;
free(del);
}
//此时,cur和next指向同一位置
if(next)
{
next=cur->next;
}
}
}
return pHead;
}