larscheng / algo

0 stars 0 forks source link

【CodeTop 04】2024-08-19 - 82. 删除排序链表中的重复元素 II #201

Open larscheng opened 3 months ago

larscheng commented 3 months ago

82. 删除排序链表中的重复元素 II

larscheng commented 3 months ago

思路

遍历节点,寻找出现重复的位置,开始从重复位置遍历进行删除

代码

    public ListNode deleteDuplicates(ListNode head) {
        ListNode dummy = new ListNode(-1,head);
        ListNode cur = dummy;

        while (cur.next!=null&&cur.next.next!=null){
            int val = cur.next.val;
            if (cur.next.next.val==val){
                //有重复节点,通过while一直删除重复节点
                // -1->1(cur)->2(cur.next)->2(cur.next.next)->2->3
                while (cur.next != null && cur.next.val == val) {
                    cur.next = cur.next.next;
                }
            }else {
                cur = cur.next;
            }
        }

        return dummy.next;
    }

复杂度