[程序员代码面试指南]链表问题-删除无序链表中重复出现的节点

题意

如题

题解

使用HashSet。
时间复杂度O(n),额外空间复杂度O(n)。

todo

使用选择排序也可以做。

代码

import java.util.HashSet;

public class Main {
    public static void main(String args[]) {
        //测试
        Node n1=new Node(2);
        Node n2=new Node(2);
        Node n3=new Node(3);
        n1.next=n2;
        n2.next=n3;
        Node head=n1;
        
        rmRepeat(head);
        
        //测试
        Node pNode=head;
        while(pNode!=null) {
            System.out.println(pNode.val);
            pNode=pNode.next;
        }
    }
    
    public static void rmRepeat(Node head) {
        if(head==null) {
            return;
        }
        HashSet<Integer> hashset=new HashSet();
        hashset.add(head.val);
        
        Node pre=head;
        Node cur=pre.next;
        while(cur!=null) {
            if(hashset.contains(cur.val)) {
                pre.next=cur.next;
            }
            else {
                hashset.add(cur.val);
                pre=cur;
            }
            cur=cur.next;
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/coding-gaga/p/10957933.html