首页 > 其他 > 详细

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

时间:2019-05-31 23:34:23      阅读:167      评论:0      收藏:0      [点我收藏+]

题意

如题

题解

使用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;
        }
    }
}

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

原文:https://www.cnblogs.com/coding-gaga/p/10957933.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!