¿Cómo podemos multiplicar dos números representados por listas vinculadas?

Puede almacenar ambos operandos en la primera lista y luego almacenar su respuesta en la segunda lista. Multiplique como lo haría normalmente (si normalmente realiza la división como lo enseñan las escuelas en los EE. UU.), Agregue cada producto intermedio a la lista de respuestas a medida que avanza. No es el método más eficiente, pero funciona.

(Supongo que ambos operandos son enteros positivos ya que están almacenados en una lista vinculada. Si necesita tener en cuenta los números negativos, simplemente verifique el primer nodo de cada lista y determine si el resultado es negativo. Luego convierta cada lista en positiva número, multiplíquelo como se describe y agregue un negativo después si es necesario.)

Código Java (mayormente no probado)

import java.util.LinkedList; import java.util.ListIterator; public class MultiplyLinkedLists { public static void main(String[] args) { LinkedList operand1 = new LinkedList(); LinkedList operand2 = new LinkedList(); operand1.addLast(new Integer(9)); operand1.addLast(new Integer(9)); operand2.addLast(new Integer(2)); operand2.addLast(new Integer(2)); boolean success = multiply(operand1, operand2); if (success) { System.out.print("The result of the multiplication is: "); System.out.println(operand2); } else { System.out.println("The two numbers could not be multiplied."); } } public static boolean multiply(LinkedList operand1, LinkedList operand2) { // Edge case yields no change if (operand1 == null || operand2 == null) { return false; } int operand1Len = operand1.size(); int operand2Len = operand2.size(); int bothOperandsLen = operand1Len + operand2Len; // Move digits from operand 2 to the end of operand 1 while (!operand2.isEmpty()) { operand1.addLast(operand2.removeFirst()); } // Rename linked lists for clarity LinkedList bothOperands = operand1; LinkedList answer = operand2; // Initialize answer to 0 answer.add(0); ListIterator operand2Iter = bothOperands.listIterator(bothOperandsLen); // Iterate over second operand's digits in reverse order for (int i = 0; i < operand2Len; i++) { int operand2Digit = operand2Iter.previous().intValue(); ListIterator operand1Iter = bothOperands.listIterator(operand1Len); // Iterate over first operand's digits in reverse order for (int j = 0; j < operand1Len; j++) { int operand1Digit = operand1Iter.previous().intValue(); int product = operand1Digit * operand2Digit; int shiftAmount = i + j; // Add the intermediate product to the answer list add(answer, product, shiftAmount); } } return true; } private static void add(LinkedList result, int product, int shiftAmount) { int resultLen = result.size(); for (int insertPositionFromRight = shiftAmount; product != 0; insertPositionFromRight++) { int digit = product % 10; product /= 10; int numNodesNeeded = insertPositionFromRight - resultLen + 1; // Expand the width of the answer linked list if necessary for (int i = 0; i  10) { newVal -= 10; product++; } result.set(resultIndex, newVal); } } } 

  // Operandos que contienen los dígitos más a la derecha en el índice 1
 multiplicar (a [1..p], b [1..q], base)
 // Asigna espacio para el resultado
   producto = [1..p + q]
 // para todos los dígitos en b
   para b_i = 1 a q 
     llevar = 0
 // para todos los dígitos en un
     para a_i = 1 a p 
       producto [a_i + b_i - 1] + = carry + a [a_i] * b [b_i]
       carry = producto [a_i + b_i - 1] / base
       producto [a_i + b_i - 1] = producto [a_i + b_i - 1] base mod
 // el último dígito proviene del acarreo final
     producto [b_i + p] + = llevar                               
   producto devuelto

Fuente: algoritmo de multiplicación

  #include 
 #include 

 / * Nodo de lista vinculada * /
 nodo de estructura
 {
	 datos int;
	 struct node * next;
 };

 / * Función para crear un nuevo nodo con datos dados * /
 struct node * newNode (int data)
 {
	 struct node * new_node = (struct node *) malloc (sizeof (struct node));
	 nuevo_nodo-> datos = datos;
	 new_node-> next = NULL;
	 return new_node;
 }

 / * Función para insertar un nodo al comienzo de la Lista Doblemente Vinculada * /
 void push (nodo de estructura ** head_ref, int new_data)
 {
	 / * asignar nodo * /
	 struct node * new_node = newNode (new_data);

	 / * enlazar la lista anterior del nuevo nodo * /
	 new_node-> next = (* head_ref);

	 / * mueve la cabeza para apuntar al nuevo nodo * /
	 (* head_ref) = nuevo_nodo;
 }

 / * Multiplica el contenido de dos listas vinculadas * /
 long multiplyTwoLists (nodo de estructura * primero, nodo de estructura * segundo)
 {
	 int num1 = 0, num2 = 0;
	 while (primer || segundo)
	 {
		 si (primero) {
			 num1 = num1 * 10 + primero-> datos;
			 primero = primero-> siguiente;
		 }
		 si (segundo)
		 {
			 num2 = num2 * 10 + segundo-> datos;
			 segundo = segundo-> siguiente;
		 }
	 }


	 devuelve num1 * num2;
 }

 // Una función de utilidad para imprimir una lista vinculada
 vacío printList (nodo de estructura * nodo)
 {
	 while (nodo! = NULL)
	 {
		 printf ("% d", nodo-> datos);
		 nodo = nodo-> siguiente;
	 }
	 printf ("\ n");
 }

 / * Programa de controlador para probar la función anterior * /
 int main (nulo)
 {
	 struct node * first = NULL;
	 struct node * second = NULL;

	 // crea la primera lista 7-> 5-> 9
	 empujar (y primero, 6);
	 empujar (y primero, 4);
	 empujar (y primero, 9);
	 printf ("La primera lista es");
	 printList (primero);

	 // crea la segunda lista 8-> 4
	 empujar (y segundo, 4);
	 empujar (y segundo, 8);
	 printf ("La segunda lista es");
	 printList (segundo);

	 // Multiplica las dos listas y mira el resultado
	 printf ("El resultado es");
	 printf ("% d", multiplyTwoLists (primer, segundo));

	 devuelve 0;
 }

Fuente: Multiplica dos números representados por listas enlazadas. – GeeksforGeeks Q&A