题目来源:链表求和
题目描述:
你有两个用链表代表的整数,其中每个节点包含一个数字。数字存储按照在原来整数中相反的顺序,使得第一个数字位于链表的开头。写出一个函数将两个整数相加,用链表形式返回和。
样例:
给出两个链表 3->1->5->null 和 5->9->2->null,返回 8->0->8->null
Java代码:
public ListNode addLists(ListNode l1, ListNode l2) {
// write your code here
int jinwei=0;
if (l1==null) {
return l2;
}
if (l2==null) {
return l1;
}
ListNode result = new ListNode(0),head = result;
while (l1!=null||l2!=null) {
if (l1==null) {
result.val = l2.val+jinwei;
jinwei=0;
if(l2.next!=null)
result.next = new ListNode(0);
result = result.next;
l2=l2.next;
}
else if (l2==null) {
result.val = l1.val+jinwei;
jinwei = 0;
if(l1.next!=null)
result.next = new ListNode(0);
result = result.next;
l1=l1.next;
}
else if (l1!=null&&l2!=null) {
if (l1.val+l2.val+jinwei>=10) {
result.val = (l1.val+l2.val+jinwei);
jinwei = 1;
}
else {
result.val = l1.val + l2.val + jinwei;
jinwei = 0;
}
if(l1.next!=null||l2.next!=null||jinwei==1)
result.next = new ListNode(0);
result = result.next;
l1=l1.next;
l2=l2.next;
}
}
if(jinwei==0)
return head;
else
{
result.val=1;
return head;
}
}