题目一:

  删除链表中的重复元素。

  思路:一是利用哈希表(HashSet),哈希表特别适合于判断集合中是否有重复的元素。二是直接使用遍历链表,使用两层for循环去遍历再来找出重复的元素。下面给出第一种方法的代码。

 1 import java.util.HashSet;
 2 
 3 public class 删除重复结点 {
 4     // 创建链表的节点
 5     private static class ListNode {
 6         ListNode next;
 7         Object value;
 8 
 9         public ListNode(Object value){
10             super();
11             this.value = value;
12         }
13     }
14 
15     public static void main(String[] args){
16         int data[] = {1, 6, 6, 7, 3, 3, 5, 3, 8, 9, 10, 10};  // 输出 1 6 7 3 5 8 9 10 
17         //哑元 空节点
18         ListNode head = new ListNode(null);
19         ListNode p = head;
20         for(int i = 0; i < data.length; i++){
21             p.next = new ListNode(data[i]);
22             //指针往下进行移动
23             p = p.next;
24         }
25         removeReptition(head);
26         ListNode p1 = head.next;
27         while(p1 != null){
28             System.out.print(p1.value + " ");
29             p1 = p1.next;
30         }
31     }
32 
33     private static void removeReptition(ListNode head){
34         ListNode p = head.next;
35         ListNode pre = head;
36         HashSet set = new HashSet();
37         //遍历哈希表
38         while(p != null){
39             if(set.contains(p.value)){
40                 pre.next = p.next;
41             }else{
42                 set.add(p.value);
43                 pre = p;
44             }
45             p = p.next;
46         }
47     }
48 }
View Code

相关文章: