标签:
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse
order, such that the 1‘s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
Given 7->1->6 + 5->9->2
. That is, 617 + 295
.
Return 2->1->9
. That is 912
.
Given 3->1->5
and 5->9->2
, return 8->0->8
.
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 /** 14 * @param l1: the first list 15 * @param l2: the second list 16 * @return: the sum list of l1 and l2 17 */ 18 public ListNode addLists(ListNode l1, ListNode l2) { 19 20 if (l1 == null) return l2; 21 if (l2 == null) return l1; 22 23 int value1 = 0; 24 int value2 = 0; 25 int carry = 0; 26 ListNode head = new ListNode(0); 27 ListNode current = head; 28 29 30 while (l1 != null || l2 != null) { 31 value1 = (l1 == null ? 0 : l1.val); 32 value2 = (l2 == null ? 0 : l2.val); 33 int value = (value1 + value2 + carry) % 10; 34 35 current.next = new ListNode(value); 36 current = current.next; 37 38 carry = (value1 + value2 + carry) / 10; 39 l1 = (l1 == null) ? null : l1.next; 40 l2 = (l2 == null) ? null : l2.next; 41 } 42 if (carry == 1) { 43 current.next = new ListNode(carry); 44 } 45 return head.next; 46 } 47 }
标签:
原文地址:http://www.cnblogs.com/beiyeqingteng/p/5675100.html