Advertisement
CR7CR7

digitsIntoLinkedList

Sep 10th, 2023
1,055
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Define a class for linked list nodes
  2. class ListNode {
  3.   constructor(val, next = null) {
  4.     this.val = val;
  5.     this.next = next;
  6.   }
  7. }
  8.  
  9. // Define a function to add two numbers represented by linked lists
  10. function addTwoNumbers(l1, l2) {
  11.   // Initialize a dummy node to store the result
  12.   let dummy = new ListNode(0);
  13.   // Initialize a pointer to the current node
  14.   let curr = dummy;
  15.   // Initialize a variable to store the carry
  16.   let carry = 0;
  17.   // Loop until both lists are exhausted or there is a carry
  18.   while (l1 || l2 || carry) {
  19.     // Get the values of the current nodes, or 0 if null
  20.     let x = l1 ? l1.val : 0;
  21.     let y = l2 ? l2.val : 0;
  22.     // Compute the sum of the values and the carry
  23.     let sum = x + y + carry;
  24.     // Update the carry
  25.     carry = Math.floor(sum / 10);
  26.     // Create a new node with the value of the sum modulo 10
  27.     curr.next = new ListNode(sum % 10);
  28.     // Move the current pointer to the next node
  29.     curr = curr.next;
  30.     // Move the list pointers to the next nodes, if exist
  31.     if (l1) l1 = l1.next;
  32.     if (l2) l2 = l2.next;
  33.   }
  34.   // Return the dummy node's next node, which is the head of the result list
  35.   return dummy.next;
  36. }
  37.  
  38. // Use +gets() to get the input from the user
  39. let input = +gets();
  40. // Split the input by space and convert each element to a number
  41. let nums = input.split(" ").map(Number);
  42. // Create two linked lists from the input numbers
  43. let l1 = new ListNode(nums[0]);
  44. let l2 = new ListNode(nums[1]);
  45. let p1 = l1;
  46. let p2 = l2;
  47. for (let i = 2; i < nums.length; i++) {
  48.   if (i % 2 == 0) {
  49.     p1.next = new ListNode(nums[i]);
  50.     p1 = p1.next;
  51.   } else {
  52.     p2.next = new ListNode(nums[i]);
  53.     p2 = p2.next;
  54.   }
  55. }
  56. // Call the function to add the two numbers and store the result list
  57. let result = addTwoNumbers(l1, l2);
  58. // Print the result list in reverse order
  59. let output = "";
  60. while (result) {
  61.   output = result.val + " " + output;
  62.   result = result.next;
  63. }
  64. console.log(output.trim());
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement