【链表】无序链表中移除重复项
1 import java.util.HashSet; 2 import java.util.Set; 3 4 public class Main { 5 6 // 从无序链表中删除重复项 7 public Node removeDup(Node node) { 8 9 if (node == null || node.next == null || node.next.next == null) { 10 return node; 11 } 12 13 Set<Integer> set = new HashSet<Integer>(); 14 15 Node pre = node; 16 Node curr = node.next; 17 18 while (curr != null) { 19 if (set.contains(curr.data)) { 20 pre.next = curr.next; 21 } else { 22 set.add(curr.data); 23 pre = curr; 24 } 25 26 curr = curr.next; 27 } 28 29 return node; 30 } 31 32 public Node createListNodes() { 33 Node node7 = new Node(7, null); 34 Node node6 = new Node(5, node7); 35 Node node5 = new Node(4, node6); 36 Node node4 = new Node(5, node5); 37 Node node3 = new Node(1, node4); 38 Node node2 = new Node(3, node3); 39 Node node1 = new Node(1, node2); 40 Node head = new Node(0, node1); // head pointer 41 42 return head; 43 } 44 45 public static void main(String[] args) { 46 Main main = new Main(); 47 Node node = main.removeDup(main.createListNodes()); 48 49 if (node != null) { 50 node = node.next; 51 while (node != null) { 52 System.out.println(node.data); 53 node = node.next; 54 } 55 } 56 } 57 }