Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Define a class for linked list nodes
- class ListNode {
- constructor(val, next = null) {
- this.val = val;
- this.next = next;
- }
- }
- // Define a function to add two numbers represented by linked lists
- function addTwoNumbers(l1, l2) {
- // Initialize a dummy node to store the result
- let dummy = new ListNode(0);
- // Initialize a pointer to the current node
- let curr = dummy;
- // Initialize a variable to store the carry
- let carry = 0;
- // Loop until both lists are exhausted or there is a carry
- while (l1 || l2 || carry) {
- // Get the values of the current nodes, or 0 if null
- let x = l1 ? l1.val : 0;
- let y = l2 ? l2.val : 0;
- // Compute the sum of the values and the carry
- let sum = x + y + carry;
- // Update the carry
- carry = Math.floor(sum / 10);
- // Create a new node with the value of the sum modulo 10
- curr.next = new ListNode(sum % 10);
- // Move the current pointer to the next node
- curr = curr.next;
- // Move the list pointers to the next nodes, if exist
- if (l1) l1 = l1.next;
- if (l2) l2 = l2.next;
- }
- // Return the dummy node's next node, which is the head of the result list
- return dummy.next;
- }
- // Use +gets() to get the input from the user
- let input = +gets();
- // Split the input by space and convert each element to a number
- let nums = input.split(" ").map(Number);
- // Create two linked lists from the input numbers
- let l1 = new ListNode(nums[0]);
- let l2 = new ListNode(nums[1]);
- let p1 = l1;
- let p2 = l2;
- for (let i = 2; i < nums.length; i++) {
- if (i % 2 == 0) {
- p1.next = new ListNode(nums[i]);
- p1 = p1.next;
- } else {
- p2.next = new ListNode(nums[i]);
- p2 = p2.next;
- }
- }
- // Call the function to add the two numbers and store the result list
- let result = addTwoNumbers(l1, l2);
- // Print the result list in reverse order
- let output = "";
- while (result) {
- output = result.val + " " + output;
- result = result.next;
- }
- console.log(output.trim());
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement