分类
LeetCode

83. Remove Duplicates from Sorted List 「删除排序链表中的重复元素」

给定一个排序链表,删除所有重复元素,使链表中的元素只出现一次。

例一:
输入: 1->1->2
输出: 1->2

例二:
输入: 1->1->2->3->3
输出: 1->2->3

/*
 * 83. Remove Duplicates from Sorted List
 * https://leetcode.com/problems/remove-duplicates-from-sorted-list/
 * https://realneo.me/83-remove-duplicates-from-sorted-list/
 */

public class DeleteDuplicates {
    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode node = head;
        node.next = new ListNode(1);
        node = node.next;
        node.next = new ListNode(2);
        node = node.next;
        node.next = new ListNode(3);
        node = node.next;
        node.next = new ListNode(3);

        DeleteDuplicates solution = new DeleteDuplicates();
        node = solution.deleteDuplicates(head);
        solution.print(node);
    }

    private void print(ListNode node) {
        for (; node != null; node = node.next) {
            System.out.print(node.val);
            System.out.print("->");
        }
        System.out.println("null");
    }

    public ListNode deleteDuplicates(ListNode head) {
        ListNode node = head;
        while (node != null) {
            if (node.next != null && node.val == node.next.val)
                node.next = node.next.next;
            else
                node = node.next;
        }
        return head;
    }
}

发表评论

电子邮件地址不会被公开。 必填项已用*标注