zoukankan      html  css  js  c++  java
  • [程序员代码面试指南]链表问题-删除无序链表中重复出现的节点

    题意

    如题

    题解

    使用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;
    		}
    	}
    }
    
  • 相关阅读:
    DataTable.AcceptChanges方法有何用处
    中山西路620号 的人才服务中心搬到 梅园路77号去了
    Congos
    ps -aux返回超过100%
    to_date如何处理毫秒?
    SNMP_802.1
    交换机
    Oracle字符编码
    CRON
    交换机
  • 原文地址:https://www.cnblogs.com/coding-gaga/p/10957933.html
Copyright © 2011-2022 走看看