链表:删除无序链表中值重复出现的节点

题目:

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

例如:1->2->3->3->4->4->2->1->1->null,删除值重复的节点之后为 1->2->3->4->null。

方法一:利用哈希表。时间复杂度O(N),空间复杂度O(N)

 1 public void remove(Node head)
 2 {
 3     if(head == null)
 4         return;
 5 
 6     HashSet<Integer> set = new HashSet<>();
 7     Node pre = head, cur = head.next;
 8     set.add(head.data);
 9     while(cur != null)
10     {
11         if(set.contains(cur.data))
12         {
13             pre.next = cur.next;
14         }
15         else
16         {
17             set.add(cur.data);
18             pre = cur;
19         }
20         cur = cur.next;
21     }
22 }

方法二:类似选择排序的过程,比如本题例子中,头节点为1,遍历头节点之后的所有节点,删除所值为1的节点;接着删除节点2之后的所有值为2的节点,以此类推。时间复杂度O(N),空间复杂度O(1)。

 1 public void remove(Node head)
 2 {
 3     if(head == null)
 4         return;
 5 
 6     Node cur = head, pre = null, next = null;
 7 
 8     while(cur != null)
 9     {
10         next = cur.next;
11         pre = cur;
12         while(next != null)
13         {
14             if(cur.data == next.data)
15             {
16                 pre.next = next.next;
17             }
18             else
19             {
20                 pre = next;
21             }
22             next = next.next;
23         }
24         cur= cur.next;
25     }
26 }

参考资料:程序员代码面试指南 IT名企算法与数据结构题目最优解,左程云

原文地址:https://www.cnblogs.com/2015110615L/p/6663486.html