You are given two non-empty linked lists representing two non-negative integers. The most significant digit comes first
and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Follow up:
What if you cannot modify the input lists? In other words, reversing the lists is not allowed.
Example:
Input: (7 -> 2 -> 4 -> 3) + (5 -> 6 -> 4)Output: 7 -> 8 -> 0 -> 7
思考: 相对题 2 的逆序相加, 该题顺序相加作如下思考:
7 -> 2 -> 4 -> 30 -> 5 -> 6 -> 4
/*** Definition for singly-linked list.* function ListNode(val) {* this.val = val;* this.next = null;* }*//*** @param {ListNode} l1* @param {ListNode} l2* @return {ListNode}*/var addTwoNumbers = function(l1, l2) {let countl1 = 0, countl2 = 0let l1List = l1let l2List = l2while(l1List) {countl1++l1List = l1List.next}while(l2List) {countl2++l2List = l2List.next}// creat the frontest Listlet tmpList = new ListNode(0)let cur = tmpListlet diff = Math.abs(countl2 - countl1)while (diff--) {cur.next = new ListNode(0)cur = cur.next}if (countl1 < countl2) {cur.next = l1l1 = tmpList.next} else if (countl2 < countl1) {cur.next = l2l2 = tmpList.next}// flag: 1 shows digit carry, 0 not;let digitCarry = 0/*** calculate the sum of l1 and l2*/function listNodeAdd(l1, l2) {if (l1 === null) returnlistNodeAdd(l1.next, l2.next)let sum = l1.val + l2.val + digitCarryif (sum >= 10) {l1.val = sum % 10digitCarry = 1} else {l1.val = sumdigitCarry = 0}}listNodeAdd(l1, l2)let result = l1if (digitCarry === 1) {result = new ListNode(1)result.next = l1}return result}
2