Programa Java para eliminar duplicados de una lista ordenada ordenada

Escriba una función que tome una lista ordenada en orden no decreciente y elimine cualquier Node duplicado de la lista. La lista solo debe recorrerse una vez. 
Por ejemplo, si la lista vinculada es 11->11->11->21->43->43->60, removeDuplicates() debería convertir la lista a 11->21->43->60. 

Algoritmo: 
recorrer la lista desde el Node principal (o inicial). Mientras atraviesa, compare cada Node con su siguiente Node. Si los datos del siguiente Node son los mismos que los del Node actual, elimine el siguiente Node. Antes de eliminar un Node, debemos almacenar el siguiente puntero del Node 

Implementación: 
las funciones que no sean removeDuplicates() son solo para crear una lista vinculada y probar removeDuplicates(). 

Java

// Java program to remove duplicates
// from a sorted linked list
class LinkedList
{
    // Head of list
    Node head; 
  
    // Linked list Node
    class Node
    {
        int data;
        Node next;
        Node(int d)
        {
            data = d;
            next = null;
        }
    }
 
    void removeDuplicates()
    {
        // Another reference to head
        Node curr = head;
 
        // Traverse list till the
        // last node
        while (curr != null)
        {
            Node temp = curr;
 
            /* Compare current node with the
               next node and keep on deleting
               them until it matches the current
               node data */
            while(temp != null &&
                  temp.data == curr.data)
            {
                temp = temp.next;
            }
 
            /* Set current node next to the next
               different element denoted by temp */
            curr.next = temp;
            curr = curr.next;
        }
    }
                     
    // Utility functions
 
    // Inserts a new Node at front of
    // the list.
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data*/
        Node new_node = new Node(new_data);
  
        // 3. Make next of new Node as head
        new_node.next = head;
  
        // 4. Move the head to point to
        // new Node
        head = new_node;
    }
 
    // Function to print linked list
     void printList()
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data+" ");
            temp = temp.next;
         } 
         System.out.println();
     }
 
    // Driver code
    public static void main(String args[])
    {
        LinkedList llist = new LinkedList();
        llist.push(20);
        llist.push(13);
        llist.push(13);
        llist.push(11);
        llist.push(11);
        llist.push(11);
         
        System.out.println(
               "List before removal of duplicates");
        llist.printList();
         
        llist.removeDuplicates();
         
        System.out.println(
               "List after removal of elements");
        llist.printList();
    }
}
// This code is contributed by Rajat Mishra

Producción:

Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20

Complejidad de tiempo: O(n) donde n es el número de Nodes en la lista enlazada dada.

Enfoque recursivo:  

Java

// Java Program to remove duplicates
// from a sorted linked list
class GFG
{
    // Link list node
    static class Node
    {
        int data;
        Node next;
    };
 
    // The function removes duplicates
    // from a sorted list
    static Node removeDuplicates(Node head)
    {
        /* Pointer to store the pointer
           of a node to be deleted*/
        Node to_free;
     
        // Do nothing if the list is empty
        if (head == null)
            return null;
 
        // Traverse the list till last node
        if (head.next != null)
        {        
            // Compare head node with next node
            if (head.data == head.next.data)
            {
                /* The sequence of steps is important.
                   to_free pointer stores the next of
                   head pointer which is to be deleted.*/
                to_free = head.next;
                head.next = head.next.next;
                removeDuplicates(head);
            }
         
            // This is tricky: only advance if no deletion
            else
            {
                removeDuplicates(head.next);
            }
        }
        return head;
    }
 
    // UTILITY FUNCTIONS
    /* Function to insert a node at the
       beginning of the linked list */
    static Node push(Node head_ref,
                     int new_data)
    {
        // Allocate node
        Node new_node = new Node();
             
        // Put in the data
        new_node.data = new_data;
                 
        // Link the old list off the
        // new node
        new_node.next = (head_ref);    
         
        // Move the head to point to the
        // new node
        (head_ref) = new_node;
         return head_ref;
    }
 
    // Function to print nodes in a given
    // linked list
    static void printList(Node node)
    {
        while (node != null)
        {
            System.out.print(" " + node.data);
            node = node.next;
        }
    }
 
    // Driver code
    public static void main(String args[])
    {
        // Start with the empty list
        Node head = null;
     
        /* Let us create a sorted linked list
           to test the functions. Created
           linked list will be 11.11.11.13.13.20 */
        head = push(head, 20);
        head = push(head, 13);
        head = push(head, 13);
        head = push(head, 11);
        head = push(head, 11);
        head = push(head, 11);                                    
 
        System.out.println("Linked list before" +
                           " duplicate removal ");
        printList(head);
 
        // Remove duplicates from linked list
        head = removeDuplicates(head);
 
        System.out.println("Linked list after" +
                           " duplicate removal ");    
        printList(head);            
    }
} 
// This code is contributed by Arnab Kundu

Producción:

Linked list before duplicate removal  11 11 11 13 13 20
Linked list after duplicate removal  11 13 20

Complejidad de tiempo: O(n), donde n es el número de Nodes en la lista enlazada dada.

Espacio auxiliar: O(n), debido a la pila recursiva donde n es el número de Nodes en la lista enlazada dada.

Otro enfoque: cree un puntero que apunte hacia la primera aparición de cada elemento y otro puntero temporal que iterará a cada elemento y cuando el valor del puntero anterior no sea igual al puntero temporal, estableceremos el puntero del anterior puntero a la primera aparición de otro Node.

A continuación se muestra la implementación del enfoque anterior:

Java

// Java program to remove duplicates
// from a sorted linked list
class LinkedList
{
    // Head of list
    Node head;
  
    // Linked list Node
    class Node
    {
        int data;
        Node next;
        Node(int d)
        {
          data = d;
          next = null;
        }
    }
 
    // Function to remove duplicates
    // from the given linked list
    void removeDuplicates()
    {
        // Two references to head temp will
        // iterate to the whole Linked List
        // prev will point towards the first
        // occurrence of every element
        Node temp = head,prev = head;
 
        // Traverse list till the last node
        while (temp != null)
        {          
           // Compare values of both pointers
           if(temp.data != prev.data)
           {
               /* if the value of prev is not equal
                  to the value of temp that means
                  there are no more occurrences of
                  the prev data. So we can set the
                  next of prev to the temp node.*/
               prev.next = temp;
               prev = temp;
           }
 
            // Set the temp to the next node
            temp = temp.next;
        }
 
        /* This is the edge case if there are more
           than one occurrences of the last element */
        if(prev != temp)
        {
            prev.next = null;
        }
    }
                     
    // Utility functions
 
    // Inserts a new Node at front
    // of the list.
    public void push(int new_data)
    {
        /* 1 & 2: Allocate the Node &
                  Put in the data */
        Node new_node = new Node(new_data);
  
        // 3. Make next of new Node as head
        new_node.next = head;
  
        // 4. Move the head to point to
        // new Node
        head = new_node;
    }
 
    // Function to print linked list
     void printList()
     {
         Node temp = head;
         while (temp != null)
         {
            System.out.print(temp.data + " ");
            temp = temp.next;
         } 
         System.out.println();
     }
 
     // Driver code
     public static void main(String args[])
     {
         LinkedList llist = new LinkedList();
         llist.push(20);
         llist.push(13);
         llist.push(13);
         llist.push(11);
         llist.push(11);
         llist.push(11);
         
         System.out.print("List before ");
         System.out.println(
                "removal of duplicates");
         llist.printList();
         
         llist.removeDuplicates();
         
         System.out.println(
                "List after removal of elements");
         llist.printList();
     }
}
// This code is contributed by Arshita

Producción:

List before removal of duplicates
11 11 11 13 13 20 
List after removal of elements
11 13 20 

Complejidad de tiempo: O(n) donde n es el número de Nodes en la lista enlazada dada.
Espacio auxiliar: O(1), no se requiere espacio adicional, por lo que es una constante.

 Otro enfoque: uso de mapas
La idea es empujar todos los valores en un mapa e imprimir sus claves.

A continuación se muestra la implementación del enfoque anterior:

Java

// Java program for the above approach
import java.io.*;
import java.util.*;
 
class Node
{
    int data;
    Node next;
    Node()
    {
        data = 0;
        next = null;
    }
}
class GFG
{   
    /* Function to insert a node at the
       beginning of the linked list */
    static Node push(Node head_ref,
                     int new_data)
    {     
        // Allocate node
        Node new_node = new Node();
       
        // Put in the data
        new_node.data = new_data;
         
        /* Link the old list off
           the new node */
        new_node.next = (head_ref);
         
        /* Move the head to point
           to the new node */
        head_ref = new_node;
        return head_ref;
    }
     
    /* Function to print nodes
       in a given linked list */
    static void printList(Node node)
    {
        while (node != null)
        {
            System.out.print(node.data + " ");
            node = node.next;
        }
    }
     
    // Function to remove duplicates
    static void removeDuplicates(Node head)
    {
        HashMap<Integer, Boolean> track = new HashMap<>();
        Node temp = head;
         
        while(temp != null)
        {
            if(!track.containsKey(temp.data))
            {
                System.out.print(temp.data + " ");
            }
            track.put(temp.data, true);
            temp = temp.next;
        }
    }
     
    // Driver Code
    public static void main (String[] args)
    {
        Node head = null;
       
        /* Created linked list will be
           11->11->11->13->13->20 */
        head = push(head, 20);
        head = push(head, 13);
        head = push(head, 13);
        head = push(head, 11);
        head = push(head, 11);
        head = push(head, 11);
        System.out.print(
               "Linked list before duplicate removal ");
        printList(head);
        System.out.print(
               "Linked list after duplicate removal  ");
        removeDuplicates(head);
    }
}
// This code is contributed by avanitrachhadiya2155

Producción:

Linked list before duplicate removal 11 11 11 13 13 20 
Linked list after duplicate removal 11 13 20 

Complejidad de tiempo: O (Número de Nodes)

Complejidad espacial: O (Número de Nodes)

Consulte el artículo completo sobre Eliminar duplicados de una lista ordenada ordenada para obtener más detalles.

Publicación traducida automáticamente

Artículo escrito por GeeksforGeeks-1 y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *