美文网首页
82. Remove Duplicates from Sorte

82. Remove Duplicates from Sorte

作者: namelessEcho | 来源:发表于2017-09-29 16:24 被阅读0次

如果遍历到尾部都是相同的值的话,只能返回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;
    }
}

相关文章

网友评论

      本文标题:82. Remove Duplicates from Sorte

      本文链接:https://www.haomeiwen.com/subject/zlwiextx.html