Dados dos números representados por dos listas enlazadas, escribe una función que devuelva la lista de suma. La lista de suma es una representación de lista enlazada de la suma de dos números de entrada. No está permitido modificar las listas. Además, no está permitido usar espacio adicional explícito (Sugerencia: use recursividad).
Ejemplo :
Input: First List: 5->6->3 Second List: 8->4->2 Output Resultant list: 1->4->0->5
Hemos discutido una solución aquí que es para listas enlazadas donde un dígito menos significativo es el primer Node de las listas y el dígito más significativo es el último Node. En este problema, el Node más significativo es el primer Node y el dígito menos significativo es el último Node y no se nos permite modificar las listas. La recursividad se usa aquí para calcular la suma de derecha a izquierda.
Los siguientes son los pasos.
1) Calcular los tamaños de dos listas vinculadas dadas.
2) Si los tamaños son iguales, calcule la suma usando la recursividad. Mantenga todos los Nodes en la pila de llamadas recursivas hasta el Node más a la derecha, calcule la suma de los Nodes más a la derecha y avance hacia el lado izquierdo.
3) Si el tamaño no es el mismo, siga los pasos a continuación:
…. a) Calcular la diferencia de tamaños de dos listas enlazadas. Que la diferencia sea diff
…. b) Mueva los Nodes diff adelante en la lista enlazada más grande. Ahora use el paso 2 para calcular la suma de la lista más pequeña y la sublista derecha (del mismo tamaño) de una lista más grande. Además, almacene el acarreo de esta suma.
…. C)Calcule la suma del acarreo (calculado en el paso anterior) con la sublista izquierda restante de una lista más grande. Los Nodes de esta suma se agregan al principio de la lista de suma obtenida en el paso anterior.
A continuación se muestra una ejecución en seco del enfoque anterior:
La imagen de abajo es la implementación del enfoque anterior.
C++
// A C++ recursive program to add two linked lists #include <bits/stdc++.h> using namespace std; // A linked List Node class Node { public: int data; Node* next; }; typedef Node node; /* A utility function to insert a node at the beginning of linked list */ void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node[(sizeof(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 linked list */ void printList(Node* node) { while (node != NULL) { cout << node->data << " "; node = node->next; } cout << endl; } // A utility function to swap two pointers void swapPointer(Node** a, Node** b) { node* t = *a; *a = *b; *b = t; } /* A utility function to get size of linked list */ int getSize(Node* node) { int size = 0; while (node != NULL) { node = node->next; size++; } return size; } // Adds two linked lists of same size // represented by head1 and head2 and returns // head of the resultant linked list. Carry // is propagated while returning from the recursion node* addSameSize(Node* head1, Node* head2, int* carry) { // Since the function assumes linked lists are of same // size, check any of the two head pointers if (head1 == NULL) return NULL; int sum; // Allocate memory for sum node of current two nodes Node* result = new Node[(sizeof(Node))]; // Recursively add remaining nodes and get the carry result->next = addSameSize(head1->next, head2->next, carry); // add digits of current nodes and propagated carry sum = head1->data + head2->data + *carry; *carry = sum / 10; sum = sum % 10; // Assign the sum to current node of resultant list result->data = sum; return result; } // This function is called after the // smaller list is added to the bigger // lists's sublist of same size. Once the // right sublist is added, the carry // must be added toe left side of larger // list to get the final result. void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result) { int sum; // If diff. number of nodes are not traversed, add carry if (head1 != cur) { addCarryToRemaining(head1->next, cur, carry, result); sum = head1->data + *carry; *carry = sum / 10; sum %= 10; // add this node to the front of the result push(result, sum); } } // The main function that adds two linked lists // represented by head1 and head2. The sum of // two lists is stored in a list referred by result void addList(Node* head1, Node* head2, Node** result) { Node* cur; // first list is empty if (head1 == NULL) { *result = head2; return; } // second list is empty else if (head2 == NULL) { *result = head1; return; } int size1 = getSize(head1); int size2 = getSize(head2); int carry = 0; // Add same size lists if (size1 == size2) *result = addSameSize(head1, head2, &carry); else { int diff = abs(size1 - size2); // First list should always be larger than second // list. If not, swap pointers if (size1 < size2) swapPointer(&head1, &head2); // move diff. number of nodes in first list for (cur = head1; diff--; cur = cur->next) ; // get addition of same size lists *result = addSameSize(cur, head2, &carry); // get addition of remaining first list and carry addCarryToRemaining(head1, cur, &carry, result); } // if some carry is still there, add a new node to the // front of the result list. e.g. 999 and 87 if (carry) push(result, carry); } // Driver code int main() { Node *head1 = NULL, *head2 = NULL, *result = NULL; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 9->9->9 int i; for (i = size1 - 1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push(&head2, arr2[i]); addList(head1, head2, &result); printList(result); return 0; } // This code is contributed by rathbhupendra
C
// A C recursive program to add two linked lists #include <stdio.h> #include <stdlib.h> // A linked List Node struct Node { int data; struct Node* next; }; typedef struct Node node; /* A utility function to insert a node at the beginning of * 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 linked list */ void printList(struct Node* node) { while (node != NULL) { printf("%d ", node->data); node = node->next; } printf("n"); } // A utility function to swap two pointers void swapPointer(Node** a, Node** b) { node* t = *a; *a = *b; *b = t; } /* A utility function to get size of linked list */ int getSize(struct Node* node) { int size = 0; while (node != NULL) { node = node->next; size++; } return size; } // Adds two linked lists of same // size represented by head1 // and head2 and returns head of // the resultant linked list. // Carry is propagated while // returning from the recursion node* addSameSize(Node* head1, Node* head2, int* carry) { // Since the function assumes // linked lists are of same // size, check any of the two // head pointers if (head1 == NULL) return NULL; int sum; // Allocate memory for sum // node of current two nodes Node* result = (Node*)malloc(sizeof(Node)); // Recursively add remaining nodes // and get the carry result->next = addSameSize(head1->next, head2->next, carry); // add digits of current nodes // and propagated carry sum = head1->data + head2->data + *carry; *carry = sum / 10; sum = sum % 10; // Assigne the sum to current // node of resultant list result->data = sum; return result; } // This function is called after // the smaller list is added // to the bigger lists's sublist // of same size. Once the // right sublist is added, the // carry must be added toe left // side of larger list to get // the final result. void addCarryToRemaining(Node* head1, Node* cur, int* carry, Node** result) { int sum; // If diff. number of nodes are // not traversed, add carry if (head1 != cur) { addCarryToRemaining(head1->next, cur, carry, result); sum = head1->data + *carry; *carry = sum / 10; sum %= 10; // add this node to the front of the result push(result, sum); } } // The main function that adds two // linked lists represented // by head1 and head2. The sum of // two lists is stored in a // list referred by result void addList(Node* head1, Node* head2, Node** result) { Node* cur; // first list is empty if (head1 == NULL) { *result = head2; return; } // second list is empty else if (head2 == NULL) { *result = head1; return; } int size1 = getSize(head1); int size2 = getSize(head2); int carry = 0; // Add same size lists if (size1 == size2) *result = addSameSize(head1, head2, &carry); else { int diff = abs(size1 - size2); // First list should always be // larger than second // list. If not, swap pointers if (size1 < size2) swapPointer(&head1, &head2); // move diff. number of nodes in first list for (cur = head1; diff--; cur = cur->next) ; // get addition of same size lists *result = addSameSize(cur, head2, &carry); // get addition of remaining first list and carry addCarryToRemaining(head1, cur, &carry, result); } // if some carry is still there, add a new node to the // front of the result list. e.g. 999 and 87 if (carry) push(result, carry); } // Driver code int main() { Node *head1 = NULL, *head2 = NULL, *result = NULL; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 9->9->9 int i; for (i = size1 - 1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push(&head2, arr2[i]); addList(head1, head2, &result); printList(result); return 0; }
Java
// A Java recursive program to add two linked lists public class linkedlistATN { class node { int val; node next; public node(int val) { this.val = val; } } // Function to print linked list void printlist(node head) { while (head != null) { System.out.print(head.val + " "); head = head.next; } } node head1, head2, result; int carry; /* A utility function to push a value to linked list */ void push(int val, int list) { node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion void addsamesize(node n, node m) { // Since the function assumes linked lists are of // same size, check any of the two head pointers if (n == null) return; // Recursively add remaining nodes and get the carry addsamesize(n.next, m.next); // add digits of current nodes and propagated carry int sum = n.val + m.val + carry; carry = sum / 10; sum = sum % 10; // Push this to result list push(sum, 3); } node cur; // This function is called after the smaller list is // added to the bigger lists's sublist of same size. // Once the right sublist is added, the carry must be // added to the left side of larger list to get the // final result. void propogatecarry(node head1) { // If diff. number of nodes are not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); int sum = carry + head1.val; carry = sum / 10; sum %= 10; // add this node to the front of the result push(sum, 3); } } int getsize(node head) { int count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked lists // represented by head1 and head2. The sum of two // lists is stored in a list referred by result void addlists() { // first list is empty if (head1 == null) { result = head2; return; } // first list is empty if (head2 == null) { result = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be larger than second list. // If not, swap pointers if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.abs(size1 - size2); // move diff. number of nodes in first list node temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } // get addition of same size lists addsamesize(cur, head2); // get addition of remaining first list and carry propogatecarry(head1); } // if some carry is still there, add a new node to // the front of the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver program to test above functions public static void main(String args[]) { linkedlistATN list = new linkedlistATN(); list.head1 = null; list.head2 = null; list.result = null; list.carry = 0; int arr1[] = { 9, 9, 9 }; int arr2[] = { 1, 8 }; // Create first list as 9->9->9 for (int i = arr1.length - 1; i >= 0; --i) list.push(arr1[i], 1); // Create second list as 1->8 for (int i = arr2.length - 1; i >= 0; --i) list.push(arr2[i], 2); list.addlists(); list.printlist(list.result); } } // This code is contributed by Rishabh Mahrsee
C#
// A C# recursive program to add two linked lists using System; public class linkedlistATN{ class node { public int val; public node next; public node(int val) { this.val = val; } } // Function to print linked list void printlist(node head) { while (head != null) { Console.Write(head.val + " "); head = head.next; } } node head1, head2, result; int carry; // A utility function to push a // value to linked list void push(int val, int list) { node newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion void addsamesize(node n, node m) { // Since the function assumes linked // lists are of same size, check any // of the two head pointers if (n == null) return; // Recursively add remaining nodes // and get the carry addsamesize(n.next, m.next); // Add digits of current nodes // and propagated carry int sum = n.val + m.val + carry; carry = sum / 10; sum = sum % 10; // Push this to result list push(sum, 3); } node cur; // This function is called after the smaller // list is added to the bigger lists's sublist // of same size. Once the right sublist is added, // the carry must be added to the left side of // larger list to get the final result. void propogatecarry(node head1) { // If diff. number of nodes are // not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); int sum = carry + head1.val; carry = sum / 10; sum %= 10; // Add this node to the front // of the result push(sum, 3); } } int getsize(node head) { int count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked // lists represented by head1 and head2. // The sum of two lists is stored in a // list referred by result void addlists() { // First list is empty if (head1 == null) { result = head2; return; } // Second list is empty if (head2 == null) { result = head1; return; } int size1 = getsize(head1); int size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be // larger than second list. // If not, swap pointers if (size1 < size2) { node temp = head1; head1 = head2; head2 = temp; } int diff = Math.Abs(size1 - size2); // Move diff. number of nodes in // first list node tmp = head1; while (diff-- >= 0) { cur = tmp; tmp = tmp.next; } // Get addition of same size lists addsamesize(cur, head2); // Get addition of remaining // first list and carry propogatecarry(head1); } // If some carry is still there, // add a new node to the front of // the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver code public static void Main(string []args) { linkedlistATN list = new linkedlistATN(); list.head1 = null; list.head2 = null; list.result = null; list.carry = 0; int []arr1 = { 9, 9, 9 }; int []arr2 = { 1, 8 }; // Create first list as 9->9->9 for(int i = arr1.Length - 1; i >= 0; --i) list.push(arr1[i], 1); // Create second list as 1->8 for(int i = arr2.Length - 1; i >= 0; --i) list.push(arr2[i], 2); list.addlists(); list.printlist(list.result); } } // This code is contributed by rutvik_56
Javascript
<script> // A javascript recursive program to add two linked lists class node { constructor(val) { this.val = val; this.next = null; } } // Function to print linked list function printlist( head) { while (head != null) { document.write(head.val + " "); head = head.next; } } var head1, head2, result; var carry; /* A utility function to push a value to linked list */ function push(val , list) { var newnode = new node(val); if (list == 1) { newnode.next = head1; head1 = newnode; } else if (list == 2) { newnode.next = head2; head2 = newnode; } else { newnode.next = result; result = newnode; } } // Adds two linked lists of same size represented by // head1 and head2 and returns head of the resultant // linked list. Carry is propagated while returning // from the recursion function addsamesize( n, m) { // Since the function assumes linked lists are of // same size, check any of the two head pointers if (n == null) return; // Recursively add remaining nodes and get the carry addsamesize(n.next, m.next); // add digits of current nodes and propagated carry var sum = n.val + m.val + carry; carry = parseInt(sum / 10); sum = sum % 10; // Push this to result list push(sum, 3); } var cur; // This function is called after the smaller list is // added to the bigger lists's sublist of same size. // Once the right sublist is added, the carry must be // added to the left side of larger list to get the // final result. function propogatecarry( head1) { // If diff. number of nodes are not traversed, add carry if (head1 != cur) { propogatecarry(head1.next); var sum = carry + head1.val; carry = parseInt(sum / 10); sum %= 10; // add this node to the front of the result push(sum, 3); } } function getsize( head) { var count = 0; while (head != null) { count++; head = head.next; } return count; } // The main function that adds two linked lists // represented by head1 and head2. The sum of two // lists is stored in a list referred by result function addlists() { // first list is empty if (head1 == null) { result = head2; return; } // first list is empty if (head2 == null) { result = head1; return; } var size1 = getsize(head1); var size2 = getsize(head2); // Add same size lists if (size1 == size2) { addsamesize(head1, head2); } else { // First list should always be larger than second list. // If not, swap pointers if (size1 < size2) { var temp = head1; head1 = head2; head2 = temp; } var diff = Math.abs(size1 - size2); // move diff. number of nodes in first list var temp = head1; while (diff-- >= 0) { cur = temp; temp = temp.next; } // get addition of same size lists addsamesize(cur, head2); // get addition of remaining first list and carry propogatecarry(head1); } // if some carry is still there, add a new node to // the front of the result list. e.g. 999 and 87 if (carry > 0) push(carry, 3); } // Driver program to test above functions head1 = null; head2 = null; result = null; carry = 0; var arr1 = [ 9, 9, 9 ]; var arr2 = [ 1, 8 ]; // Create first list as 9->9->9 for (i = arr1.length - 1; i >= 0; --i) push(arr1[i], 1); // Create second list as 1->8 for (i = arr2.length - 1; i >= 0; --i) push(arr2[i], 2); addlists(); printlist(result); // This code is contributed by todaysgaurav </script>
1 0 1 7
Complejidad de tiempo : O(m+n) donde m y n son los tamaños de dos listas enlazadas dadas.
Complejidad espacial : O (m + n) para la pila de llamadas
Enfoque iterativo:
Esta implementación no tiene ninguna sobrecarga de llamadas recursivas, lo que significa que es una solución iterativa.
Dado que necesitamos comenzar a agregar números de la última de las dos listas vinculadas. Entonces, aquí usaremos la estructura de datos de pila para implementar esto.
- Primero haremos dos pilas de las dos listas enlazadas dadas.
- Luego, ejecutaremos un bucle hasta que ambas pilas queden vacías.
- en cada iteración, mantenemos la pista del acarreo.
- Al final, si carry>0, eso significa que necesitamos un Node adicional al comienzo de la lista resultante para acomodar este carry.
C++
// C++ Iterative program to add two linked lists #include <bits/stdc++.h> using namespace std; // A linked List Node class Node { public: int data; Node* next; }; // to push a new node to linked list void push(Node** head_ref, int new_data) { /* allocate node */ Node* new_node = new Node[(sizeof(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; } // to add two new numbers Node* addTwoNumList(Node* l1, Node* l2) { stack<int> s1,s2; while(l1!=NULL){ s1.push(l1->data); l1=l1->next; } while(l2!=NULL){ s2.push(l2->data); l2=l2->next; } int carry=0; Node* result=NULL; while(s1.empty()==false || s2.empty()==false){ int a=0,b=0; if(s1.empty()==false){ a=s1.top();s1.pop(); } if(s2.empty()==false){ b=s2.top();s2.pop(); } int total=a+b+carry; Node* temp=new Node(); temp->data=total%10; carry=total/10; if(result==NULL){ result=temp; }else{ temp->next=result; result=temp; } } if(carry!=0){ Node* temp=new Node(); temp->data=carry; temp->next=result; result=temp; } return result; } // to print a linked list void printList(Node *node) { while (node != NULL) { cout<<node->data<<" "; node = node->next; } cout<<endl; } // Driver Code int main() { Node *head1 = NULL, *head2 = NULL; int arr1[] = {5, 6, 7}; int arr2[] = {1, 8}; int size1 = sizeof(arr1) / sizeof(arr1[0]); int size2 = sizeof(arr2) / sizeof(arr2[0]); // Create first list as 5->6->7 int i; for (i = size1-1; i >= 0; --i) push(&head1, arr1[i]); // Create second list as 1->8 for (i = size2-1; i >= 0; --i) push(&head2, arr2[i]); Node* result=addTwoNumList(head1, head2); printList(result); return 0; }
Java
// Java Iterative program to add // two linked lists import java.io.*; import java.util.*; class GFG{ static class Node { int data; Node next; public Node(int data) { this.data = data; } } static Node l1, l2, result; // To push a new node to linked list public static void push(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } public static void push1(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers public static Node addTwoNumbers() { Stack<Integer> stack1 = new Stack<>(); Stack<Integer> stack2 = new Stack<>(); while (l1 != null) { stack1.add(l1.data); l1 = l1.next; } while (l2 != null) { stack2.add(l2.data); l2 = l2.next; } int carry = 0; Node result = null; while (!stack1.isEmpty() || !stack2.isEmpty()) { int a = 0, b = 0; if (!stack1.isEmpty()) { a = stack1.pop(); } if (!stack2.isEmpty()) { b = stack2.pop(); } int total = a + b + carry; Node temp = new Node(total % 10); carry = total / 10; if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { Node temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list public static void printList() { while (result != null) { System.out.print(result.data + " "); result = result.next; } System.out.println(); } // Driver code public static void main(String[] args) { int arr1[] = { 5, 6, 7 }; int arr2[] = { 1, 8 }; int size1 = 3; int size2 = 2; // Create first list as 5->6->7 int i; for(i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for(i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); } } // This code is contributed by RohitOberoi
Python3
# Python Iterative program to add # two linked lists class Node: def __init__(self,val): self.data = val self.next = None l1, l2, result = None,None,0 # To push a new node to linked list def push(new_data): global l1 # Allocate node new_node = Node(0) # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = l1 # Move the head to point to the new node l1 = new_node def push1(new_data): global l2 # Allocate node new_node = Node(0) # Put in the data new_node.data = new_data # Link the old list off the new node new_node.next = l2 # Move the head to point to # the new node l2 = new_node # To add two new numbers def addTwoNumbers(): global l1,l2,result stack1 = [] stack2 = [] while (l1 != None): stack1.append(l1.data) l1 = l1.next while (l2 != None): stack2.append(l2.data) l2 = l2.next carry = 0 result = None while (len(stack1) != 0 or len(stack2) != 0): a,b = 0,0 if (len(stack1) != 0): a = stack1.pop() if (len(stack2) != 0): b = stack2.pop() total = a + b + carry temp = Node(total % 10) carry = total // 10 if (result == None): result = temp else: temp.next = result result = temp if (carry != 0): temp = Node(carry) temp.next = result result = temp return result # To print a linked list def printList(): global result while (result != None): print(result.data ,end = " ") result = result.next # Driver code arr1 = [ 5, 6, 7 ] arr2 = [ 1, 8 ] size1 = 3 size2 = 2 # Create first list as 5->6->7 for i in range(size1-1,-1,-1): push(arr1[i]) # Create second list as 1->8 for i in range(size2-1,-1,-1): push1(arr2[i]) result = addTwoNumbers() printList() # This code is contributed by shinjanpatra
C#
// C# Iterative program to add // two linked lists using System; using System.Collections; class GFG{ public class Node { public int data; public Node next; public Node(int data) { this.data = data; } } static Node l1, l2, result; // To push a new node to linked list public static void push(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } public static void push1(int new_data) { // Allocate node Node new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers public static Node addTwoNumbers() { Stack stack1 = new Stack(); Stack stack2 = new Stack(); while (l1 != null) { stack1.Push(l1.data); l1 = l1.next; } while (l2 != null) { stack2.Push(l2.data); l2 = l2.next; } int carry = 0; Node result = null; while (stack1.Count != 0 || stack2.Count != 0) { int a = 0, b = 0; if (stack1.Count != 0) { a = (int)stack1.Pop(); } if (stack2.Count != 0) { b = (int)stack2.Pop(); } int total = a + b + carry; Node temp = new Node(total % 10); carry = total / 10; if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { Node temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list public static void printList() { while (result != null) { Console.Write(result.data + " "); result = result.next; } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int []arr1 = { 5, 6, 7 }; int []arr2 = { 1, 8 }; int size1 = 3; int size2 = 2; // Create first list as 5->6->7 int i; for(i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for(i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); } } // This code is contributed by pratham76
Javascript
<script> // javascript Iterative program to add // two linked lists class Node { constructor(val) { this.data = val; this.next = null; } } var l1, l2, result; // To push a new node to linked list function push(new_data) { // Allocate node var new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l1; // Move the head to point to the new node l1 = new_node; } function push1(new_data) { // Allocate node var new_node = new Node(0); // Put in the data new_node.data = new_data; // Link the old list off the new node new_node.next = l2; // Move the head to point to // the new node l2 = new_node; } // To add two new numbers function addTwoNumbers() { var stack1 = []; var stack2 = []; while (l1 != null) { stack1.push(l1.data); l1 = l1.next; } while (l2 != null) { stack2.push(l2.data); l2 = l2.next; } var carry = 0; var result = null; while (stack1.length != 0 || stack2.length != 0) { var a = 0, b = 0; if (stack1.length != 0) { a = stack1.pop(); } if (stack2.length != 0) { b = stack2.pop(); } var total = a + b + carry; var temp = new Node(total % 10); carry = parseInt(total / 10); if (result == null) { result = temp; } else { temp.next = result; result = temp; } } if (carry != 0) { var temp = new Node(carry); temp.next = result; result = temp; } return result; } // To print a linked list function printList() { while (result != null) { document.write(result.data + " "); result = result.next; } document.write(); } // Driver code var arr1 = [ 5, 6, 7 ]; var arr2 = [ 1, 8 ]; var size1 = 3; var size2 = 2; // Create first list as 5->6->7 var i; for (var i = size1 - 1; i >= 0; --i) push(arr1[i]); // Create second list as 1->8 for (i = size2 - 1; i >= 0; --i) push1(arr2[i]); result = addTwoNumbers(); printList(); // This code contributed by umadevi9616 </script>
5 8 5
Complejidad de tiempo: O (nlogn)
Aquí, n es el número de elementos en la lista más grande. Agregar/eliminar elementos en una pila es una operación O(log n) y tenemos que agregar/eliminar 3*n elementos como máximo. por lo tanto, nuestra complejidad de tiempo total se convierte en O (nlogn).
Espacio Auxiliar: O(n)
Se utiliza espacio adicional para almacenar los elementos de la lista en la pila.
Artículo relacionado: Suma dos números representados por listas enlazadas | Conjunto 1
Escriba comentarios si encuentra algo incorrecto o si desea compartir más información sobre el tema tratado anteriormente.
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