题目描述
有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
代码
import java.util.*;
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Plus {
public ListNode plusAB(ListNode a, ListNode b) {
// write code here
ListNode ret = new ListNode(-1);
ListNode result = ret;
int up = 0;
while(a != null && b != null)
{
int sum = a.val + b.val + up;
if(sum > 9)
{
up = 1;
ret.next = new ListNode(sum - 10);
}
else
{
up = 0;
ret.next = new ListNode(sum);
}
ret = ret.next;
a = a.next;
b = b.next;
}
if(a != null)
{
ListNode newNode = a.next;
ret.next = new ListNode(a.val + up);
ret.next.next = newNode;
}
else if(b != null)
{
ListNode newNode = b.next;
ret.next = new ListNode(b.val + up);
ret.next.next = newNode;
}
else
{
if(up == 1)
{
ret.next = new ListNode(1);
}
}
return result.next;
}
}