删除链表中所有重复元素

public ListNode deleteDuplication(ListNode pHead){
  //LinkedHashMap可以按照输入的顺序进行输出
  LinkedHashMap map = new LinkedHashMap<>();
  ListNode current = pHead;
  while(current != null){
    if(!map.containsKey(current.val)){
      map.put(current.val,1);
    }else{
      int times = map.get(current.val);
      times++;
      map.put(current.val,times);
    }
    current = current.next;
  }

  ListNode newHead = null;
  ListNode point = null;
  boolean isHead = true;
  set set = map.keySet();
  Iterator it = set.iterator();

  //根据map中的值,只用出现一次的值来构造新表
  while(it.hasNext()){
    int temp = it.next();
    if(map.get(temp) == 1){
      ListNode currentNode = new ListNode(temp);
      if(isHead){
        newHead = curentNode;
        point = currentNode;
        isHead = false;
        continue;
      }
      point.next = currentNode;
      point = currentNode;
    }
  }
  return newHead;
}

 

转载于:https://www.cnblogs.com/strawqqhat/p/10602155.html

你可能感兴趣的:(删除链表中所有重复元素)