删除无序单链表中值重复出现的节点

    xiaoxiao2025-05-15  3

    题目:给定一个无序单链表的头结点head,删除其中值重复出现的节点。 例如:1->2->3->3->4->4->2->1->1->null,删除重复的节点之后为1->2->3->4->null。

    思路: 利用哈希表。时间复杂度为O(n),额外空间复杂度为O(n)。

    头节点是直接放入HashSet中的,因为肯定不重复。 当哈希表中没有当前节点值时,要将当前节点的值加入,为以后判断做准备;当哈希表已经存在当前节点值,直接跳过,不管即可(当然也可以加,HashSet有自动查重功能)。

    java参考代码如下:

    package zuo_chapter2; import java.util.HashSet; public class P77_RemoveRepeat { public static class Node{ int val; Node next; public Node(int val){ this.val=val; this.next=null; } } public static Node removeRep(Node head){ if(head==null) return null; HashSet<Integer> set=new HashSet<>(); Node pre=head; Node cur=head.next; set.add(head.val); while (cur!=null){ if(set.contains(cur.val)){ pre.next=cur.next; }else{ set.add(cur.val); pre=cur; } cur=cur.next; } return head; } public static void printNode(Node head){ if(head==null) System.out.println("no Node!"); Node cur=head; while (cur.next!=null){ System.out.print(cur.val+"->"); cur=cur.next; } System.out.println(cur.val); } public static void main(String[] args) { Node head=new Node(1); head.next=new Node(2); head.next.next=new Node(2); head.next.next.next=new Node(3); head.next.next.next.next=new Node(3); printNode(head); printNode(removeRep(head)); } }
    最新回复(0)