You are given two linked lists representing two non-negative numbers. 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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解题思路:
新建一个链表, 然后一位一位相加, 注意进位的处理就好~还有最后一个节点相加的时候, 有进位要加上去.
给p.next赋值的时候要new ListNode啊..别傻傻的直接等于..跟我似的..lol
1 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 2 if(l1 == null) 3 return l2; 4 if(l2 == null) 5 return l1; 6 int add = 0; 7 ListNode head = new ListNode(0); 8 ListNode p = head; 9 10 while(l1 != null && l2 != null){ 11 p.next = new ListNode((l1.val + l2.val + add) % 10); 12 add = (l1.val + l2.val + add) / 10; 13 l1 = l1.next; 14 l2 = l2.next; 15 p = p.next; 16 } 17 while(l1 != null && l2 == null){ 18 p.next = new ListNode((l1.val + add) % 10); 19 add = (l1.val + add) / 10; 20 l1 = l1.next; 21 p = p.next; 22 } 23 while(l1 == null && l2 != null){ 24 p.next = new ListNode((l2.val + add) % 10); 25 add = (l2.val + add) / 10; 26 l2 = l2.next; 27 p = p.next; 28 } 29 if(add == 1){ 30 p.next = new ListNode(1); 31 32 } 33 return head.next; 34 }