/**
* 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) {
// Start typing your Java solution below
// DO NOT write main() function
int val = l1.val + l2.val;
ListNode ret = new ListNode(val % 10);
ListNode lastnode = ret;
while(l1.next != null || l2.next !=null){
int newval = 0;
if (l1.next != null){
l1 = l1.next;
newval += l1.val;
}
if (l2.next != null){
l2 = l2.next;
newval += l2.val;
}
if (val > 9) newval ++;
if (lastnode == ret){
ret.next = new ListNode(newval % 10);
lastnode = ret.next;
}
else {
lastnode.next = new ListNode(newval % 10);
lastnode = lastnode.next;
}
val = newval;
}
if (val > 9){
lastnode.next = new ListNode(1);
lastnode = lastnode.next;
}
lastnode.next = null;
return ret;
}
}
没有评论:
发表评论