leetcod82 删除排序链表中的重复元素II 迭代+递归解法

题目详情

在这里插入图片描述

迭代解法

	public ListNode deleteDuplicates(ListNode head) {
    
    
        if(head==null||head.next==null) return head; 
        ListNode newHead = new ListNode(-101);
        newHead.next = head;
        ListNode pre = newHead;
        ListNode cur = head;
        ListNode next = cur.next;
        //这样写会漏掉一个
        while(next!=null){
    
    
            if(cur.val!=next.val){
    
    //不重复出现时
                if(cur.next==next){
    
    
                    pre.next = cur;
                    pre = cur; 
                }
                cur = next;//不管怎样, cur要移动, 不然3344就会一直cur==3  
            }
            next = next.next;
        }
        if(cur.next==next){
    
    //如果最后一个不重复
            pre.next = cur;
            pre = cur;
        } 
        pre.next = null;
        //要判断最后一个是否可以
        //如果是修改原来的链表, 那么要最后置空, 不然很容易出问题
        return newHead.next;
    }
  • 迭代的方法代码更麻烦一些, 这里是O(1)的空间, 如果O(n)空间会简单很多
  • 思路是, pre指向上一个可用节点, cur指向重复节点的第一个节点, next指向下一个节点
  • 当next.val == cur.val时, 则说明重复, 则next前进, 直到不等, 遇到第一个不等的数, 此时根据cur.next?=next来判断cur的值是否重复, 如果重复, 则加入我们的pre.next
  • 这里无论重复与否, 最终都要更新cur到next
  • 然后最后一个节点要单独判断, 判断它是否重复
  • 然后因为在原链表上进行操作, 得将pre.next置为空, 针对于12344这种情况, 如果不置空, 结果就是12344了, 就错了

递归解法

  • 递归解法逻辑以及代码比较简单
	public ListNode deleteDuplicates(ListNode head) {
    
    
        if(head==null||head.next==null) return head; 
        ListNode p = head;
        while(p!=null&&p.val==head.val) p = p.next;//找到第一个和head不等的节点p
        if(head.next==p) head.next = deleteDuplicates(p);//如果p是head的next,说明不重复
        else head = deleteDuplicates(p);//重复
        return head;
    }

猜你喜欢

转载自blog.csdn.net/qq_34687559/article/details/118752837