codeTop100题(38)82. 删除排序链表中的重复元素 II

71 阅读1分钟

1. 题目

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

2. 分析

image.png

如果当前节点有重复,则将当前节点和后面重复的节点全部删除。 我们可以通过多个指针,一次遍历删除

  1. 首先定义出前置节点 image.png

  2. 发现next重复,将next一直指向到null或者不相等 image.png

  3. 将pre的next指向next,head移动到next位置 image.png

  4. 发现next与head不相等,将pre后移,head后移

3. 代码

public ListNode deleteDuplicates(ListNode head) {
    if (null == head) {
        return head;
    }
    ListNode newHead = new ListNode(0);
    newHead.next = head;
    ListNode pre = newHead;
    ListNode next;

![image.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/49ab501887c6464686bc4ca5685b7931~tplv-k3u1fbpfcp-jj-mark:0:0:0:0:q75.image#?w=1582&h=640&s=78631&e=png&b=fdfdfd)
    while (null != head) {
        next = head.next;
        if (null != next && next.val == head.val) {
            while (next!= null && next.val == head.val) {
                next = next.next;
            }
            pre.next = next;
            head = next;

        } else {
            pre = head;
            head = next;
        }
    }
    return newHead.next;
}