面试题 02.01. 移除重复节点

面试题 02.01. 移除重复节点

Scroll Down

移除重复节点

编写代码,移除未排序链表中的重复节点。保留最开始出现的节点。

示例1:

 输入:[1, 2, 3, 3, 2, 1]
 输出:[1, 2, 3]

示例2:

 输入:[1, 1, 1, 1, 2]
 输出:[1, 2]

思路

将出现的重复数字添加到set中,判断是否重复出现

解答

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode removeDuplicateNodes(ListNode head) {
        Set<Integer> set = new HashSet<>();
        
        if (head == null) return null;
        ListNode pre = null, newHead = head;
        while (head != null) {
            ListNode next = head.next;
            if (!set.contains(head.val)) {
                set.add(head.val);
                pre = head;
                head = next;
            } else {
                pre.next = next;
                head = next;
            }
        }

        return newHead;
    }
}