Multiplying Numbers Represented by Linked Lists
Mon Mar 18 2024
findNumber:
This essential method traverses through the linked list, assembling the list's nodes into a complete number. It employs a modulo operation to maintain the number within a manageable range, addressing potential overflow issues by adhering to a specific modulo base. This careful construction ensures that each node's value is appropriately placed in its decimal position, converting the list into a numeric representation for further operations.
multiplyLL:
A straightforward yet effective function designed to multiply the numeric values extracted from two linked lists. By leveraging the findNumber method to obtain these values, it accomplishes the multiplication operation, showcasing how data structured as a linked list can be manipulated to perform arithmetic calculations seamlessly.
1class Node {
2  constructor(val) {
3    this.data = val;
4    this.next = null;
5  }
6}
7
8class LinkedList {
9  constructor() {
10    this.head = null;
11  }
12  addLast(val) {
13    let newNode = new Node(val);
14    if (!this.head) {
15      this.head = newNode;
16      return;
17    }
18    let current = this.head;
19    while (current.next) {
20      current = current.next;
21    }
22    current.next = newNode;
23  }
24  print() {
25    let current = this.head;
26    while (current) {
27      console.log(current.data);
28      current = current.next;
29    }
30    current.next = newNode;
31  }
32  findNumber() {
33    const MOD = Math.pow(10, 9) + 7;
34    let current = this.head;
35    let n1 = 0;
36    while (current) {
37      n1 = (n1 * 10 + current.data) % MOD;
38      current = current.next;
39    }
40    return n1;
41  }
42}
43const linkedlist = new LinkedList();
44const linkedlist1 = new LinkedList();
45
46linkedlist.addLast(9);
47linkedlist.addLast(4);
48linkedlist.addLast(6);
49console.log(linkedlist.findNumber());
50linkedlist1.addLast(8);
51linkedlist1.addLast(4);
52console.log(linkedlist1.findNumber());
53
54function multiplyLL(a, b) {
55  return a * b;
56}
57
58console.log(multiplyLL(linkedlist.findNumber(), linkedlist1.findNumber()));
59