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

吞佛童子2022年10月10日
  • algorithm
  • list
小于 1 分钟

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

难度: 🌗

问题描述

img_3.png


解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode deleteDuplicates(ListNode head) {
        // 思路:
        // 看清楚题目要求
        if(head == null || head.next == null) {
            return head;
        }
        ListNode pre = new ListNode(101);
        ListNode res = pre;
        pre.next = head;
        ListNode cur = head;
        while(cur != null && cur.next != null) {
            if(cur.val == cur.next.val) {
                cur = getNext(cur);
                pre.next = cur;
            } else {
                pre = cur;
                cur = cur.next;
            }
        }
        return res.next;
    }

    private ListNode getNext(ListNode cur) {
        // 找到 val != cur.val 的下一个节点
        ListNode res = cur;
        int val = cur.val;
        while(res != null) {
            if(res.val == val) {
                res = res.next;
            } else {
                break;
            }
        }
        return res;
    }
}

输出

img_2.png

上次编辑于: 2022/10/10 下午8:43:48
贡献者: liuxianzhishou