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().
Javascript
<script> // Javascript program to remove duplicates // from a sorted linked list // Linked list Node class Node { constructor(d) { this.data = d; this.next = null; } } // Head of list let head = new Node(); function removeDuplicates() { // Another reference to head let curr = head; // Traverse list till the last node while (curr != null) { let 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. function push(new_data) { /* 1 & 2: Allocate the Node & Put in the data */ let 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 function printList() { let temp = head; while (temp != null && temp.data) { document.write(temp.data+" "); temp = temp.next; } document.write("<br>"); } // Driver code push(20) push(13) push(13) push(11) push(11) push(11) document.write( "List before removal of duplicates "); printList(); removeDuplicates(); document.write( "List after removal of elements "); printList(); // This code is contributed by unknown2108 </script>
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(1)
Enfoque recursivo:
Javascript
<script> // JavaScript Program to remove duplicates // from a sorted linked list // Link list node class Node { constructor(val) { this.data = val; this.next = null; } } // The function removes duplicates // from a sorted list function removeDuplicates(head) { /* Pointer to store the pointer of a node to be deleted */ var 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 function push(head_ref, new_data) { // Allocate node */ var 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 */ function printList(node) { while (node != null) { document.write(" " + node.data); node = node.next; } } /* Driver code */ /* Start with the empty list */ var 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); document.write("Linked list before" + " duplicate removal <br/>"); printList(head); /* Remove duplicates from linked list */ head = removeDuplicates(head); document.write("<br/>Linked list after" + " duplicate removal <br/>"); printList(head); // This code is contributed by todaysgaurav </script>
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:
Javascript
<script> // javascript program to remove duplicates // from a sorted linked list // head of list var head; // Linked list Node class Node { constructor(val) { this.data = val; this.next = null; } } // Function to remove duplicates // from the given linked list function removeDuplicates() { // Two references to head // temp will iterate to the // whole Linked List // prev will point towards // the first occurrence of every element var 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. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var 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 */ function printList() { var temp = head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } document.write("<br/>"); } /* Driver program to test above functions */ push(20); push(13); push(13); push(11); push(11); push(11); document.write("List before "); document.write("removal of duplicates<br/>"); printList(); removeDuplicates(); document.write("List after removal of elements<br/>"); printList(); // This code contributed by aashish1995 </script>
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:
Javascript
<script> // Javascript program for the above approach class Node { constructor() { this.data = 0; this.next = null; } } /* Function to insert a node at the beginning of the linked * list */ function push(head_ref, new_data) { /* allocate node */ let 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 */ function printList(node) { while (node != null) { document.write(node.data + " "); node = node.next; } } // Function to remove duplicates function removeDuplicates(head) { let track = new Map(); let temp = head; while(temp != null) { if (!track.has(temp.data)) { document.write(temp.data + " "); } track.set(temp.data, true); temp = temp.next; } } // Driver Code let 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); document.write("Linked list before duplicate removal "); printList(head); document.write("<br>Linked list after duplicate removal "); removeDuplicates(head); // This code is contributed by patel2127 </script>
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