Search for a command to run...
Propagate addition carry backward using list reversal or recursion
Initial Linked List
Initial list representing the number 159. We start with carry = 1.
Iterative (Reversal)
1class Solution {2 reverseList(head) {3 let prev = null;4 let current = head;5 let next = null;6 while (current !== null) {7 next = current.next;8 current.next = prev;9 prev = current;10 current = next;11 }12 return prev;13 }14 15 addOne(head) {16 // Step 1: Reverse list17 head = this.reverseList(head);18 19 let current = head;20 let carry = 1; 21 22 // Step 2: Add 1 with carry23 while (current !== null) {24 let sum = current.val + carry;//carry: 125 carry = Math.floor(sum / 10);26 current.val = sum % 10;27 28 if (carry === 0) {29 break;30 }31 32 if (current.next === null && carry !== 0) {33 current.next = new ListNode(carry);34 break;35 }36 current = current.next;37 }38 39 // Step 3: Reverse back40 head = this.reverseList(head);41 return head;42 }43}