如果遍历到尾部都是相同的值的话,只能返回null了,所以这里要对POS1是否还在head位置进行一次判断。还有是 pre的移动处理,只有当确认了pos1.val!=pos2.val时,才是需要对pre进行移动处理的,否则只是改变pre的next指针的指向
class Solution {
public ListNode deleteDuplicates(ListNode head) {
if(head==null||head.next==null)return head;
ListNode dummy =new ListNode(0);
dummy.next=head;
ListNode pre = dummy;
ListNode pos1 =head;
ListNode pos2 = pos1.next;
while(pos2!=null)
{
if(pos1.val!=pos2.val)
{
pre=pre.next;
pos1=pos1.next;
pos2=pos1.next;
}
else
{
while(pos2!=null&&pos2.val==pos1.val)
pos2=pos2.next;
if(pos2==null)
{
pre.next=null;
}
else
{
pre.next=pos2;
pos1=pos2;
pos2=pos1.next;
}
}
}
return pos1==head?null:dummy.next;
}
}