链表加法。
题目来源:https://leetcode.com/problems/add-two-numbers
中文版:https://leetcode-cn.com/problems/add-two-numbers/
题目难度:Medium
题目 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 contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
解答1[Java]: 核心思想 代码 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 class Solution { public ListNode addTwoNumbers (ListNode l1, ListNode l2) { ListNode head = null , tail = null ; int carry = 0 ; while (l1 != null || l2 != null ) { int n1 = l1 != null ? l1.val : 0 ; int n2 = l2 != null ? l2.val : 0 ; int sum = n1 + n2 + carry; if (head == null ) { head = tail = new ListNode (sum % 10 ); } else { tail.next = new ListNode (sum % 10 ); tail = tail.next; } carry = sum / 10 ; if (l1 != null ) { l1 = l1.next; } if (l2 != null ) { l2 = l2.next; } } if (carry > 0 ) { tail.next = new ListNode (carry); } return head; } }
解答2[Java]:递归思路 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 public class Problem2Solution2 { class ListNode { int val; ListNode next; ListNode() { } ListNode(int val) { this .val = val; } ListNode(int val, ListNode next) { this .val = val; this .next = next; } } public ListNode addTwoNumbers (ListNode l1, ListNode l2) { if (l1 == null && l2 == null ) { return null ; } if (l1 == null ) { l1 = new ListNode (0 ); } if (l2 == null ) { l2 = new ListNode (0 ); } int rval = l1.val + l2.val; if (rval >= 10 ) { rval = rval % 10 ; if (l1.next != null ) { l1.next.val += 1 ; } else { l1.next = new ListNode (1 ); } } return new ListNode (rval, addTwoNumbers(l1.next, l2.next)); } }
进阶:链表中的数是正向存储的 思路1:给较短链表的长度和较长链表的长度补齐,补的高位节点的值都设为0。