Add Two Numbers
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
注意:1.得第一个数字位于链表的开头.2.进位 3. 1->3->null 9->6->null 的情况 答案为 0->0->1->null. 2->null 8->9->null 0->0->1 2->null 8->9-6>null 0->0->7->null
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { val = x; } 7 * } 8 */ 9 public class Solution { 10 public ListNode addTwoNumbers(ListNode l1, ListNode l2) { 11 if (l1 == null && l2 == null) { 12 return null; 13 } 14 if (l1 == null) { 15 return l2; 16 } 17 if (l2 == null) { 18 return l1; 19 } 20 ListNode dummy = new ListNode(0); 21 ListNode head = dummy; 22 boolean carry = false; 23 while (l1 != null && l2 != null) { 24 int value = 0; 25 if (carry) { 26 value = l1.val + l2.val + 1; 27 carry = false; 28 } else { 29 value = l1.val + l2.val; 30 } 31 if (value >= 10) { 32 carry = true; 33 value = value - 10; 34 } 35 head.next = new ListNode(value); 36 head = head.next; 37 l1 = l1.next; 38 l2 = l2.next; 39 } 40 while (l1 != null) { 41 int val = l1.val; 42 if (carry) { 43 carry = false; 44 val++; 45 } 46 if (val >= 10) { 47 carry = true; 48 val = val - 10; 49 } 50 head.next = new ListNode(val); 51 head = head.next; 52 l1 = l1.next; 53 } 54 while (l2 != null) { 55 int val = l2.val; 56 if (carry) { 57 carry = false; 58 val++; 59 } 60 if (val >= 10) { 61 carry = true; 62 val = val - 10; 63 } 64 head.next = new ListNode(val); 65 head = head.next; 66 l2 = l2.next; 67 } 68 if (l1 == null && l2 == null && carry) { 69 head.next = new ListNode(1); 70 head = head.next; 71 } 72 head.next = null; 73 return dummy.next; 74 } 75 }

浙公网安备 33010602011771号