美文网首页
面试题 02.01. 移除重复节点

面试题 02.01. 移除重复节点

作者: xy啊_46b8 | 来源:发表于2020-04-30 21:38 被阅读0次

题目描述:

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

示例1:

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

输出:[1,2,3]

示例2:

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

输出:[1,2]

提示:

1、链表长度在[0, 20000]范围内。

2、链表元素在[0, 20000]范围内。


import java.util.HashSet;

import java.util.Set;

public class otoo {

    private static Setset =new HashSet<>();

    public ListNoderemoveDuplicateNodes(ListNode head) {

        if (head ==null)

        return null;

        if (!set.contains(head.val)) {

            set.add(head.val);

            head.next = removeDuplicateNodes(head.next);

            return head;

        }

    else {

        return removeDuplicateNodes(head.next);

    }

}

    public static void main(String[] args){

        int[] index = {1,1,1,1,2};

        ListNode.LinkedList list =new ListNode.LinkedList();

        for (int i=0;i<index.length;i++){

            ListNode.createLN(list,index[i]);

        }

        otoo oord =new otoo();

        oord.removeDuplicateNodes(list.head);

        System.out.print(set);

    }

}

关于单链表的Java实现,见链接单链表的Java实现

相关文章

网友评论

      本文标题:面试题 02.01. 移除重复节点

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