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

题目:

给定一个无序单链表的头节点head,删除其中值重复出现的节点。

要求使用两种方法:

方法一:如果链表长度为N,时间复杂度达到O(N)。

方法二:额外空间复杂度为O(1)。

方法一:

利用哈希表。

	public static void removeRep(Node head){
		if(head==null)
			return;
		HashSet<Integer> set=new HashSet<>();
		Node pre=null;
		Node cur=head;
		Node next=head.next;
		while(cur!=null){
			if(set.contains(cur.val)){
				pre.next=cur.next;
			}else{
				set.add(cur.val);
				pre=cur;
			}
			cur=cur.next;
		}
		
	}

方法二:

public static void removeRep2(Node head){
		Node pre=null;
		Node cur=head;
		Node next=head.next;
		while(cur!=null){
			pre=cur;
			next=cur.next;
			while(next!=null){
				if(cur.val==next.val){
					pre.next=next.next;
					next=next.next;
				}else{
					pre=next;
					next=next.next;
				}
			}
			cur=cur.next;
		}
	}
posted @ 2016-03-15 20:36  小魔仙  阅读(362)  评论(0编辑  收藏  举报