Leetcode 题目解析之 Remove Duplicates from Sorted List

2022-01-14 11:38:36 浏览数 (3)

Given a sorted linked list, delete all duplicates such that each element appear only once.

For example,

Given 1->1->2, return 1->2.

Given 1->1->2->3->3, return 1->2->3.

代码语言:javascript复制
    public ListNode deleteDuplicates(ListNode head) {

        if (head == null) {
            return null;
        }

        if (head.next == null) {
            return head;
        }

        ListNode node = head;

        while (node.next != null) {

            // 如果元素不重复,跳过
            if (node.val != node.next.val) {
                node = node.next;
            } else {
                // 重复,则跳过下一个
                while (node.next != null && node.val == node.next.val) {
                    node.next = node.next.next;
                }
            }
        }

        return head;
    }

1 人点赞