Dadas dos listas enlazadas, cree listas de unión e intersección que contengan la unión y la intersección de los elementos presentes en las listas dadas. El orden de los elementos en las listas de salida no importa.
Ejemplo:
Input: List1: 10->15->4->20 List2: 8->4->2->10 Output: Intersection List: 4->10 Union List: 2->8->20->4->15->10
Método 1 (Simple):
Los siguientes son algoritmos simples para obtener listas de unión e intersección respectivamente.
Intersección (lista1, lista2)
Inicializa la lista de resultados como NULL. Recorra list1 y busque cada elemento en list2, si el elemento está presente en list2, luego agregue el elemento al resultado.
Unión (lista1, lista2):
inicialice una nueva lista y almacene los datos de la primera y la segunda lista para configurar para eliminar los datos duplicados
y luego almacenarlos en nuestra nueva lista y devolver su cabeza.
C++
// C++ program to find union // and intersection of two unsorted // linked lists #include "bits/stdc++.h" using namespace std; /* Link list node */ struct Node { int data; struct Node* next; Node(int x) { data = x; next = NULL; } }; /* A utility function to insert a node at the beginning ofa linked list*/ void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */ bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */ struct Node* getUnion(struct Node* head1, struct Node* head2) { struct Node* ans = new Node(-1); struct Node* head = ans; set<int> st; while (head1 != NULL) { st.insert(head1->data); head1 = head1->next; } while (head2 != NULL) { st.insert(head2->data); head2 = head2->next; } for (auto it : st) { struct Node* t = new Node(it); ans->next = t; ans = ans->next; } head = head->next; return head; } /* Function to get intersection of two linked lists head1 and head2 */ struct Node* getIntersection(struct Node* head1, struct Node* head2) { struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result; } /* A utility function to insert a node at the beginning of a linked list*/ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct 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; } /* A utility function to print a linked list*/ void printList(struct Node* node) { while (node != NULL) { cout << " " << node->data; node = node->next; } } bool isPresent(struct Node* head, int data) { struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0; } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /*create a linked lists 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); cout << "\n First list is " << endl; printList(head1); cout << "\n Second list is " << endl; printList(head2); cout << "\n Intersection list is " << endl; printList(intersecn); cout << "\n Union list is " << endl; printList(unin); return 0; } // This code is contributed by zishanahmad786
C
// C program to find union // and intersection of two unsorted // linked lists #include <stdbool.h> #include <stdio.h> #include <stdlib.h> /* Link list node */ struct Node { int data; struct Node* next; }; /* A utility function to insert a node at the beginning ofa linked list*/ void push(struct Node** head_ref, int new_data); /* A utility function to check if given data is present in a list */ bool isPresent(struct Node* head, int data); /* Function to get union of two linked lists head1 and head2 */ struct Node* getUnion(struct Node* head1, struct Node* head2) { struct Node* result = NULL; struct Node *t1 = head1, *t2 = head2; // Insert all elements of // list1 to the result list while (t1 != NULL) { push(&result, t1->data); t1 = t1->next; } // Insert those elements of list2 // which are not present in result list while (t2 != NULL) { if (!isPresent(result, t2->data)) push(&result, t2->data); t2 = t2->next; } return result; } /* Function to get intersection of two linked lists head1 and head2 */ struct Node* getIntersection(struct Node* head1, struct Node* head2) { struct Node* result = NULL; struct Node* t1 = head1; // Traverse list1 and search each element of it in // list2. If the element is present in list 2, then // insert the element to result while (t1 != NULL) { if (isPresent(head2, t1->data)) push(&result, t1->data); t1 = t1->next; } return result; } /* A utility function to insert a node at the beginning of a linked list*/ void push(struct Node** head_ref, int new_data) { /* allocate node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct 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; } /* A utility function to print a linked list*/ void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(struct Node* head, int data) { struct Node* t = head; while (t != NULL) { if (t->data == data) return 1; t = t->next; } return 0; } /* Driver program to test above function*/ int main() { /* Start with the empty list */ struct Node* head1 = NULL; struct Node* head2 = NULL; struct Node* intersecn = NULL; struct Node* unin = NULL; /*create a linked lists 10->15->5->20 */ push(&head1, 20); push(&head1, 4); push(&head1, 15); push(&head1, 10); /*create a linked lists 8->4->2->10 */ push(&head2, 10); push(&head2, 2); push(&head2, 4); push(&head2, 8); intersecn = getIntersection(head1, head2); unin = getUnion(head1, head2); printf("\n First list is \n"); printList(head1); printf("\n Second list is \n"); printList(head2); printf("\n Intersection list is \n"); printList(intersecn); printf("\n Union list is \n"); printList(unin); return 0; }
Java
// Java program to find union and // intersection of two unsorted // linked lists class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Function to get Union of 2 Linked Lists */ void getUnion(Node head1, Node head2) { Node t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!isPresent(head, t2.data)) push(t2.data); t2 = t2.next; } } void getIntersection(Node head1, Node head2) { Node result = null; Node t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (isPresent(head2, t1.data)) push(t1.data); t1 = t1.next; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Inserts a node at start of linked list */ 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; } /* A utility function that returns true if data is present in linked list else return false */ boolean isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList unin = new LinkedList(); LinkedList intersecn = new LinkedList(); /*create a linked lists 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); System.out.println("First List is"); llist1.printList(); System.out.println("Second List is"); llist2.printList(); System.out.println("Intersection List is"); intersecn.printList(); System.out.println("Union List is"); unin.printList(); } } /* This code is contributed by Rajat Mishra */
C#
// C# program to find union and // intersection of two unsorted // linked lists using System; class LinkedList { public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Function to get Union of 2 Linked Lists */ void getUnion(Node head1, Node head2) { Node t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!isPresent(head, t2.data)) push(t2.data); t2 = t2.next; } } void getIntersection(Node head1, Node head2) { Node t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (isPresent(head2, t1.data)) push(t1.data); t1 = t1.next; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ 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; } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Driver code*/ public static void Main(string[] args) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList unin = new LinkedList(); LinkedList intersecn = new LinkedList(); /*create a linked lists 10->15->5->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); Console.WriteLine("First List is"); llist1.printList(); Console.WriteLine("Second List is"); llist2.printList(); Console.WriteLine("Intersection List is"); intersecn.printList(); Console.WriteLine("Union List is"); unin.printList(); } } // This code is contributed by rutvik_56.
Javascript
<script> //Javascript program to find union and // intersection of two unsorted // linked lists /* Linked list Node*/ class Node { constructor(d) { this.data = d; this.next = null; } } class LinkedList{ constructor(){ this.head=null; } /* Inserts a node at start of linked list */ 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 = this.head; /* 4. Move the head to point to new Node */ this.head = new_node; } /* A utility function that returns true if data is present in linked list else return false */ isPresent(head, data) { var t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } /* Function to get Union of 2 Linked Lists */ getUnion(head1, head2) { var t1 = head1, t2 = head2; // insert all elements of list1 in the result while (t1 != null) { this.push(t1.data); t1 = t1.next; } // insert those elements of list2 // that are not present while (t2 != null) { if (!this.isPresent(this.head, t2.data)) this.push(t2.data); t2 = t2.next; } } getIntersection(head1, head2) { var result = null; var t1 = head1; // Traverse list1 and search each // element of it in list2. // If the element is present in // list 2, then insert the // element to result while (t1 != null) { if (this.isPresent(head2, t1.data)) this.push(t1.data); t1 = t1.next; } } /* Utility function to print list */ printList() { var temp = this.head; while (temp != null) { document.write(temp.data + " "); temp = temp.next; } } } const llist1 = new LinkedList(); const llist2 = new LinkedList(); const unin = new LinkedList(); const intersecn = new LinkedList(); /*create a linked lists 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked lists 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersecn.getIntersection(llist1.head, llist2.head); unin.getUnion(llist1.head, llist2.head); document.write("First List is "); llist1.printList(); document.write("Second List is "); llist2.printList(); document.write("Intersection List is "); intersecn.printList(); document.write("Union List is "); unin.printList(); //This code is contributed by shruti456rawal </script>
First list is 10 15 4 20 Second list is 8 4 2 10 Intersection list is 4 10 Union list is 2 8 20 4 15 10
Análisis de Complejidad:
- Complejidad temporal: O(m*n).
Aquí ‘m’ y ‘n’ son el número de elementos presentes en la primera y segunda lista respectivamente.
Para unión: para cada elemento en la lista-2, verificamos si ese elemento ya está presente en la lista resultante hecha usando la lista-1.
Para intersección: para cada elemento en la lista-1, verificamos si ese elemento también está presente en la lista-2. - Espacio Auxiliar: O(1).
No se utiliza ninguna estructura de datos para almacenar valores.
Método 2 (usar clasificación por combinación):
En este método, los algoritmos para Unión e Intersección son muy similares. Primero, ordenamos las listas dadas, luego recorremos las listas ordenadas para obtener la unión y la intersección.
Los siguientes son los pasos a seguir para obtener listas de unión e intersección.
- Ordene la primera Lista Vinculada utilizando la ordenación por fusión. Este paso toma tiempo O(mLogm). Consulte esta publicación para obtener detalles de este paso.
- Ordene la segunda lista enlazada utilizando la ordenación por combinación. Este paso toma tiempo O(nLogn). Consulte esta publicación para obtener detalles de este paso.
- Escanea linealmente ambas listas ordenadas para obtener la unión y la intersección. Este paso toma O(m + n) tiempo. Este paso se puede implementar usando el mismo algoritmo que el algoritmo de arreglos ordenados discutido aquí .
La complejidad temporal de este método es O(mLogm + nLogn), que es mejor que la complejidad temporal del método 1.
Método 3 (usar hashing):
Union (list1, list2)
Inicialice la lista de resultados como NULL y cree una tabla hash vacía. Recorra ambas listas una por una, para cada elemento visitado, mire el elemento en la tabla hash. Si el elemento no está presente, insértelo en la lista de resultados. Si el elemento está presente, ignórelo.
Intersección (lista1, lista2)
Inicialice la lista de resultados como NULL y cree una tabla hash vacía. poligonal list1. Para cada elemento visitado en list1, inserte el elemento en la tabla hash. Atraviese list2, para cada elemento que se visita en list2, busque el elemento en la tabla hash. Si el elemento está presente, insértelo en la lista de resultados. Si el elemento no está presente, ignórelo.
Ambos métodos anteriores asumen que no hay duplicados.
Java
// Java code for Union and Intersection of two // Linked Lists import java.util.HashMap; import java.util.HashSet; class LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { System.out.print(temp.data + " "); temp = temp.next; } System.out.println(); } /* Inserts a node at start of linked list */ 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; } public void append(int new_data) { if (this.head == null) { Node n = new Node(new_data); this.head = n; return; } Node n1 = this.head; Node n2 = new Node(new_data); while (n1.next != null) { n1 = n1.next; } n1.next = n2; n2.next = null; } /* A utility function that returns true if data is present in linked list else return false */ boolean isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } LinkedList getIntersection(Node head1, Node head2) { HashSet<Integer> hset = new HashSet<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop stores all the elements of list1 in hset while (n1 != null) { if (hset.contains(n1.data)) { hset.add(n1.data); } else { hset.add(n1.data); } n1 = n1.next; } // For every element of list2 present in hset // loop inserts the element into the result while (n2 != null) { if (hset.contains(n2.data)) { result.push(n2.data); } n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2) { // HashMap that will store the // elements of the lists with their counts HashMap<Integer, Integer> hmap = new HashMap<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop inserts the elements and the count of // that element of list1 into the hmap while (n1 != null) { if (hmap.containsKey(n1.data)) { int val = hmap.get(n1.data); hmap.put(n1.data, val + 1); } else { hmap.put(n1.data, 1); } n1 = n1.next; } // loop further adds the elements of list2 with // their counts into the hmap while (n2 != null) { if (hmap.containsKey(n2.data)) { int val = hmap.get(n2.data); hmap.put(n2.data, val + 1); } else { hmap.put(n2.data, 1); } n2 = n2.next; } // Eventually add all the elements // into the result that are present in the hmap for (int a : hmap.keySet()) { result.append(a); } return result; } /* Driver program to test above functions */ public static void main(String args[]) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList union = new LinkedList(); LinkedList intersection = new LinkedList(); /*create a linked list 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked list 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersection = intersection.getIntersection(llist1.head, llist2.head); union = union.getUnion(llist1.head, llist2.head); System.out.println("First List is"); llist1.printList(); System.out.println("Second List is"); llist2.printList(); System.out.println("Intersection List is"); intersection.printList(); System.out.println("Union List is"); union.printList(); } } // This code is contributed by Kamal Rawal
C#
// C# code for Union and Intersection of two // Linked Lists using System; using System.Collections; using System.Collections.Generic; class LinkedList { public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } /* Utility function to print list */ void printList() { Node temp = head; while (temp != null) { Console.Write(temp.data + " "); temp = temp.next; } Console.WriteLine(); } /* Inserts a node at start of linked list */ 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; } public void append(int new_data) { if (this.head == null) { Node n = new Node(new_data); this.head = n; return; } Node n1 = this.head; Node n2 = new Node(new_data); while (n1.next != null) { n1 = n1.next; } n1.next = n2; n2.next = null; } /* A utility function that returns true if data is present in linked list else return false */ bool isPresent(Node head, int data) { Node t = head; while (t != null) { if (t.data == data) return true; t = t.next; } return false; } LinkedList getIntersection(Node head1, Node head2) { HashSet<int> hset = new HashSet<int>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop stores all the elements of list1 in hset while (n1 != null) { if (hset.Contains(n1.data)) { hset.Add(n1.data); } else { hset.Add(n1.data); } n1 = n1.next; } // For every element of list2 present in hset // loop inserts the element into the result while (n2 != null) { if (hset.Contains(n2.data)) { result.push(n2.data); } n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2) { // HashMap that will store the // elements of the lists with their counts SortedDictionary<int, int> hmap = new SortedDictionary<int, int>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); // loop inserts the elements and the count of // that element of list1 into the hmap while (n1 != null) { if (hmap.ContainsKey(n1.data)) { hmap[n1.data]++; } else { hmap[n1.data]= 1; } n1 = n1.next; } // loop further adds the elements of list2 with // their counts into the hmap while (n2 != null) { if (hmap.ContainsKey(n2.data)) { hmap[n2.data]++; } else { hmap[n2.data]= 1; } n2 = n2.next; } // Eventually add all the elements // into the result that are present in the hmap foreach(int a in hmap.Keys) { result.append(a); } return result; } /* Driver program to test above functions */ public static void Main(string []args) { LinkedList llist1 = new LinkedList(); LinkedList llist2 = new LinkedList(); LinkedList union = new LinkedList(); LinkedList intersection = new LinkedList(); /*create a linked list 10->15->4->20 */ llist1.push(20); llist1.push(4); llist1.push(15); llist1.push(10); /*create a linked list 8->4->2->10 */ llist2.push(10); llist2.push(2); llist2.push(4); llist2.push(8); intersection = intersection.getIntersection(llist1.head, llist2.head); union = union.getUnion(llist1.head, llist2.head); Console.WriteLine("First List is"); llist1.printList(); Console.WriteLine("Second List is"); llist2.printList(); Console.WriteLine("Intersection List is"); intersection.printList(); Console.WriteLine("Union List is"); union.printList(); } } //This code is contributed by pratham76
First List is 10 15 4 20 Second List is 8 4 2 10 Intersection List is 10 4 Union List is 2 4 20 8 10 15
Análisis de Complejidad:
- Complejidad Temporal: O(m+n).
Aquí ‘m’ y ‘n’ son el número de elementos presentes en la primera y segunda lista respectivamente.
Para la unión: recorra ambas listas, almacene los elementos en Hash-map y actualice el recuento respectivo.
Para la intersección: primero recorra la lista 1, almacene sus elementos en Hash-map y luego, para cada elemento de la lista 2, verifique si ya está presente en el mapa. Esto lleva tiempo O(1). - Espacio Auxiliar: O(m+n).
Uso de la estructura de datos Hash-map para almacenar valores.
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