This problem can be converted to be reverse first then reverse back after summing. Be careful of the carry digit, and update it after sum calculation.
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//boolean nextAdd = false;
int carry = 0;
ListNode newHead = new ListNode(Integer.MIN_VALUE);
ListNode node = newHead;
while(l1 != null && l2 != null){
int curValue = 0;
if(l1.val + l2.val + carry > 9){
curValue = (carry + l1.val + l2.val - 10);
carry = 1;
}else{
curValue = l1.val + l2.val + carry;
carry = 0;
}
node.next = new ListNode(curValue);
l1 = l1.next;
l2 = l2.next;
node = node.next;
}
while(l1 != null){
int curValue = 0;
if(l1.val + carry > 9){
curValue = l1.val + carry - 10;
carry = 1;
}else{
curValue = l1.val + carry;
carry = 0;
}
node.next = new ListNode(curValue);
l1 = l1.next;
node = node.next;
}
while(l2 != null){
int curValue = 0;
if(l2.val + carry > 9){
curValue = l2.val + carry - 10;
carry = 1;
}else{
curValue = l2.val + carry;
carry = 0;
}
node.next = new ListNode(curValue);
l2 = l2.next;
node = node.next;
}
if(carry == 1){
node.next = new ListNode(1);
node = node.next;
}
return newHead.next;
}
}
没有评论:
发表评论