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
/**
* 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) {
if(l1 == null && l2 == null)
return null;
ListNode head = new ListNode(-1);
ListNode[] p = new ListNode[]{null, null};
p[1] = head;
int sum = 0;
boolean carray = false;
for(;l1 != null && l2 != null;l1 = l1.next, l2 = l2.next){
if(carray == false){
sum = l1.val+l2.val;
if(sum >= 10){
p[1].val = sum % 10;
carray = true;
}else{
p[1].val = sum;
}
}else{
sum = l1.val+l2.val + 1;
if(sum >= 10){
p[1].val = sum % 10;
}else{
p[1].val = sum;
carray = false;
}
}
//increase
p[0] = p[1];
p[1] = p[1].next = new ListNode(-1);
}
//consider longer one
ListNode ph = null;
if(l1 != null)
ph = l1;
else
ph = l2;
for(;ph != null;ph = ph.next){
if(carray){
sum = ph.val + 1;
if(sum >= 10){
p[1].val = sum % 10;
}else{
p[1].val = sum;
carray = false;
}
}else{
p[1].val = ph.val;
}
//increase
p[0] = p[1];
p[1] = p[1].next = new ListNode(-1);
}
//considering carray
if(carray){
p[1].val = 1;
}else{
p[0].next = null;
}
return head;
}
}
类似于01字符串相加
p[2]的存在是为了删除多余创建的ListNode