📌  相关文章
📜  用链表表示的两个数字相乘的Java程序

📅  最后修改于: 2022-05-13 01:57:44.456000             🧑  作者: Mango

用链表表示的两个数字相乘的Java程序

给定两个由链表表示的数字,编写一个函数,返回这两个链表的乘积。

例子:

Input: 9->4->6
        8->4
Output: 79464

Input: 3->2->1
        1->2
Output: 3852

解决方案
遍历两个列表并生成需要相乘的数字,然后返回两个数字的相乘值。
从链表表示生成数字的算法:

1) Initialize a variable to zero
2) Start traversing the linked list
3) Add the value of first node to this variable
4) From the second node, multiply the variable by 10
   and also take modulus of this value by 10^9+7
   and then add the value of the node to this 
   variable.
5) Repeat step 4 until we reach the last node of the list. 

将上述算法与两个链表一起使用以生成数字。

下面是用链表表示的两个数字相乘的程序:

Java
// Java program to Multiply two numbers
// represented as linked lists
import java.util.*;
  
public class GFG{
  
// Linked list node
static class Node
{
    int data;
    Node next;
          
    Node(int data)
    {
        this.data = data;
        next = null;
    }
}
  
// Multiply contents of two linked lists
static long multiplyTwoLists(Node first, 
                             Node second)
{
    long N = 1000000007;
    long num1 = 0, num2 = 0;
  
    while (first != null || 
           second !=  null)
    {            
        if(first != null)
        {
            num1 = (((num1) * 10) % N + 
                      first.data);
            first = first.next;
        }
              
        if(second != null)
        {
            num2 = (((num2) * 10) % N + 
                      second.data);
            second = second.next;
        }            
    }
    return (((num1 % N) * 
             (num2 % N)) % N);
}
  
// A utility function to print a 
// linked list
static void printList(Node node)
{
    while(node != null)
    {
        System.out.print(node.data);
        if(node.next != null)
            System.out.print("->");
        node = node.next;
    }
    System.out.println();
}
  
// Driver code
public static void main(String args[])
{
    // Create first list 9->4->6
    Node first = new Node(9);
    first.next = new Node(4);
    first.next.next = new Node(6);
    System.out.print("First List is: ");
    printList(first);
  
    // Create second list 8->4
    Node second = new Node(8);
    second.next = new Node(4);
    System.out.print("Second List is: ");
    printList(second);
  
    // Multiply the two lists and see result
    System.out.print("Result is: ");
    System.out.println(multiplyTwoLists(first, second));
}
}
// This code is contributed by adityapande88


输出:

First List is: 9->4->6
Second List is: 8->4
Result is: 79464

有关详细信息,请参阅有关将链接列表表示的两个数字相乘的完整文章!