Problem
You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in forward 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.
Example
Given 6->1->7 + 2->9->5. That is, 617 + 295.
Return 9->1->2. That is, 912.
Tags
- Linked List
- High Precision
Solution
public class Solution {
/*
* @param l1: The first list.
* @param l2: The second list.
* @return: the sum list of l1 and l2.
*/
public ListNode addLists2(ListNode l1, ListNode l2) {
// write your code here
ListNode n1 = reverse(l1);
ListNode n2 = reverse(l2);
ListNode node = new ListNode(0);
ListNode n3 = node;
int sum = 0, carry = 0;
while (n1 != null || n2 != null || carry != 0) {
int v1 = n1 == null ? 0 : n1.val;
int v2 = n2 == null ? 0 : n2.val;
n1 = n1 == null ? null : n1.next;
n2 = n2 == null ? null : n2.next;
sum = v1 + v2 + carry;
ListNode cur = new ListNode(sum % 10);
carry = sum / 10;
n3.next = cur;
n3 = cur;
}
return reverse(node.next);
}
private ListNode reverse(ListNode head) {
ListNode newHead = null;
while (head != null) {
ListNode temp = head.next;
head.next = newHead;
newHead = head;
head = temp;
}
return newHead;
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。