You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order 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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
两数相加。
这题不难,思路是直接做加法,因为linked list给你的时候头结点是数字的最低位,不需要做reverse之类的操作,记得最后判断是不是还有额外的一个进位。
时间O(n)
空间O(1)
JavaScript实现
1 /** 2 * @param {ListNode} l1 3 * @param {ListNode} l2 4 * @return {ListNode} 5 */ 6 var addTwoNumbers = function (l1, l2) { 7 let dummy = new ListNode(0); 8 let cur = dummy; 9 let carry = 0; 10 let p1 = l1; 11 let p2 = l2; 12 while (p1 !== null || p2 !== null) { 13 if (p1 !== null) { 14 carry += p1.val; 15 p1 = p1.next; 16 } 17 if (p2 !== null) { 18 carry += p2.val; 19 p2 = p2.next; 20 } 21 cur.next = new ListNode(carry % 10); 22 carry = parseInt(carry / 10); 23 cur = cur.next; 24 } 25 if (carry === 1) { 26 cur.next = new ListNode(1); 27 } 28 return dummy.next; 29 };
Java实现
1 class Solution { 2 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 3 ListNode dummy = new ListNode(0); 4 ListNode cur = dummy; 5 int sum = 0; 6 ListNode p1 = l1; 7 ListNode p2 = l2; 8 while (p1 != null || p2 != null) { 9 if (p1 != null) { 10 sum += p1.val; 11 p1 = p1.next; 12 } 13 if (p2 != null) { 14 sum += p2.val; 15 p2 = p2.next; 16 } 17 cur.next = new ListNode(sum % 10); 18 sum /= 10; 19 cur = cur.next; 20 } 21 if (sum == 1) cur.next = new ListNode(1); 22 return dummy.next; 23 } 24 }
相关题目