题目
给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
解答:
public class Solution { public ListNode addTwoNums(ListNode l1, ListNode l2) { if(null == l1 || null == l2) { return null; } ListNode header = new ListNode(0); ListNode point = header; int temp = 0; while(l1 != null && l2 != null) { int sum = carry+l1.val+l2.val; point.next = new ListNode(sum % 10); temp= sum/10; l1 = l1.next; l2 = l2.next; point = point.next; } while(l1 != null) { int sum = carry+l1.val; point.next = new ListNode(sum%10); temp = sum/10; l1 = l1.next; point = point.next; } while(l2 != null) { int sum = carry+l2.val; point.next = new ListNode(sum%10); temp = sum/10; l2 = l2.next; point = point.next; } if(temp != 0) { point.next = new ListNode(carry); } return header.next; } }