Remove duplicates from an unsorted linked list

前端 未结 19 1117
梦如初夏
梦如初夏 2020-12-09 06:54
import java.util.*;
/*
 *  Remove duplicates from an unsorted linked list
 */
public class LinkedListNode {  
    public int data;  
    public LinkedListNode next;          


        
19条回答
  •  天命终不由人
    2020-12-09 07:23

    Iterate through the linked list, adding each element to a hash table. When we discover a duplicate element, we remove the element and continue iterating. We can do this all in one pass since we are using a linked list.

    The following solution takes O(n) time, n is the number of element in the linked list.

    public static void deleteDups (LinkedListNode n){
      Hashtable table = new Hashtable();
      LinkedListNode previous = null;
      while(n!=null){
          if(table.containsKey(n.data)){
              previous.next = n.next;
          } else {
              table.put(n.data, true);
              previous = n;
          }
          n = n.next;
      }
    }
    

提交回复
热议问题