LeetCode刷题系列 -- 面试题 02.01. 移除重复节点

题目

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

示例1:

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

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

链表长度在[0, 20000]范围内。
链表元素在[0, 20000]范围内。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicate-node-lcci
 

思路:定义两个临时节点 tmp1 与 tmp2 ,tmp1 为 tmp2的上游节点。利用一个 set 用于存储链表中出现过的节点

    把 head 节点存储到 set 中,tmp2 指向 head.next ,tmp1 指向 head 

  1、如果set 包含 tmp2 节点,则 从链表中删除 tmp2 节点,并将tmp2节点往下移动一位,tmp1节点不懂

   2、如果set 不包含 tmp2 节点,则 把 tmp2的值保存到 set 中将tmp1与tmp2节点往下移动一位

 

Java代码:

    public ListNode removeDuplicateNodes(ListNode head) {
        Set  set = new HashSet<>();
        if(head==null){
            return head;
        }
        ListNode tmp1 = head;
        ListNode tmp2 = head;
        set.add(tmp2.val);
        tmp2 = tmp2.next;
        while (tmp2!=null){
            if(set.contains(tmp2.val)){
                tmp1.next = tmp2.next;
            }else {
                set.add(tmp2.val);
                tmp1 = tmp1.next;
            }
            tmp2 = tmp2.next;

        }
        return head;
    }

 

你可能感兴趣的:(LeetCode,链表,移除重复节点)