鏈表問題13——刪除無序單鏈表中值重複出現的節點

題目

 給定一個無序單鏈表的頭節點head,刪除其中值重複出現的節點。

原鏈表 刪除後
1->2->3->3->4->2->4->1 1->2->3->4

要求:

 方法一:時間複雜度O(N)

方法二:額外空間複雜度O(1)


思路

方法一:利用哈希表

  1. 先將頭節點加入哈希表中
  2. 依次遍歷鏈表節點,每次先查看當前節點的值是否在哈希表中,如果在,就跳過當前節點,否則就加入哈希表中

源碼

public class Node{
	public int value;
	public Node next;
	public Node(int data){
		this.value=data;
	} 
}

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

 

發佈了57 篇原創文章 · 獲贊 34 · 訪問量 6474
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章