移除重复节点

作者: 历十九喵喵喵 | 来源:发表于2020-11-30 12:05 被阅读0次

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

    解法:

    Set 去重

    新建一个Set集合,从链表的头开始遍历,如果Set 集合中出现重复的元素,我们则过滤掉。

    关于链表的遍历, 新建一个ListNode 节点当链表的头节点,然后开始 while 循环遍历,当cur 为空或者 cur.next 为空时,则遍历完成,所以遍历的条件是 cur.next!=null || cur !=null

    代码:

    public ListNode removeDuplicateNodes(ListNode head) {

            Set<Integer> set = new HashSet<>();

            ListNode cur = head;

            while (cur != null && cur.next != null) {

                set.add(cur.val);

                if (set.contains(cur.next.val))

                    cur.next = cur.next.next;

                else

                    cur = cur.next;

            }

            return head;

        }

    作者:sdwwld

    链接:力扣

    相关文章

      网友评论

        本文标题:移除重复节点

        本文链接:https://www.haomeiwen.com/subject/yqplwktx.html