有两个用链表表示的整数,每个结点包含一个数位。这些数位是反向存放的,也就是个位排在链表的首部。编写函数对这两个整数求和,并用链表形式返回结果。
给定两个链表ListNode* A,ListNode* B,请返回A+B的结果(ListNode*)。
测试样例:
{1,2,3},{3,2,1}
返回:{4,4,4}
解析:需要考虑到进位,两个链表长度不同,和进位如果发生在链表尾部时需要多加一位的情况。
代码:
public ListNode plusAB(ListNode a, ListNode b) {
ListNode aTemp = a;
ListNode bTemp = b;
int push = 0;
ListNode ret = null;
ListNode temp = null;
while (aTemp != null && bTemp != null) {
if (ret == null) {
ret = new ListNode(0);
temp = ret;
} else {
temp.next = new ListNode(0);
temp = temp.next;
}
temp.val = (aTemp.val + bTemp.val + push) % 10;
push = (aTemp.val + bTemp.val + push) >= 10 ? 1 : 0;
aTemp = aTemp.next;
bTemp = bTemp.next;
}
while (aTemp != null) {
if (ret == null) {
ret = new ListNode(0);
temp = ret;
} else {
temp.next = new ListNode(0);
temp = temp.next;
}
temp.val = (aTemp.val + push) % 10;
push = (aTemp.val + push) >= 10 ? 1 : 0;
aTemp = aTemp.next;
}
while (bTemp != null) {
if (ret == null) {
ret = new ListNode(0);
temp = ret;
} else {
temp.next = new ListNode(0);
temp = temp.next;
}
temp.val = (bTemp.val + push) % 10;
push = (bTemp.val + push) >= 10 ? 1 : 0;
bTemp = bTemp.next;
}
if (push != 0) {
temp.next = new ListNode(push);
}
temp = ret;
while (temp != null) {
temp = temp.next;
}
return ret;
}