Remove duplicates from an unsorted linked list

前端 未结 19 1114
梦如初夏
梦如初夏 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:36

    You can use the following java method to remove duplicates:

    1) With complexity of O(n^2)

    public void removeDuplicate(Node head) {
        Node temp = head;
        Node duplicate = null;                //will point to duplicate node
        Node prev = null;                     //prev node to duplicate node
        while (temp != null) {                //iterate through all nodes       
            Node curr = temp;
            while (curr != null) {                     //compare each one by one
                /*in case of duplicate skip the node by using prev node*/
                if (curr.getData() == temp.getData() && temp != curr) {        
                    duplicate = curr;
                    prev.setNext(duplicate.getNext());
                }
                prev = curr;
                curr = curr.getNext();
            }
            temp = temp.getNext();
        }
    }
    

    Input:1=>2=>3=>5=>5=>1=>3=>

    Output:1=>2=>3=>5=>

    2)With complexity of O(n) using hash table.

    public void removeDuplicateUsingMap(Node head) {
        Node temp = head;
        Map hash_map = new HashMap(); //create a hash map
        while (temp != null) {  
            if (hash_map.get(temp.getData()) == null) {  //if key is not set then set is false
                hash_map.put(temp.getData(), false);
            } else {                                   //if key is already there,then delete the node
                deleteNode(temp,head);
            }
            temp = temp.getNext();
        }
    
    }
    
    public void deleteNode(Node n, Node start) {
            Node temp = start;
            if (n == start) {
                start = null;
            } else {
                while (temp.getNext() != n) {
                    temp = temp.getNext();
                }
    
                temp.setNext(n.getNext());
    
            }
        }
    

    Input:1=>2=>3=>5=>5=>1=>3=>

    Output:1=>2=>3=>5=>

提交回复
热议问题