public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
// Start typing your Java solution below
// DO NOT write main() function
ListNode head = null;
ListNode next = null;
ListNode cur = null;
int sum = 0;
while(l1 != null && l2 != null){
int total = sum + l1.val + l2.val;
sum = total / 10;
int value = total %10;
if(head == null){
head = new ListNode(value);
cur = head;
}else{
next = new ListNode(value);
cur.next = next;
cur = next;
}
l1 = l1.next;
l2 = l2.next;
}
while(l1 != null){
int total = sum + l1.val;
sum = total / 10;
int value = total %10;
if(head == null){
head = new ListNode(value);
cur = head;
}else{
next = new ListNode(value);
cur.next = next;
cur = next;
}
l1 = l1.next;
}
while(l2 != null){
int total = sum + l2.val;
sum = total / 10;
int value = total %10;
if(head == null){
head = new ListNode(value);
cur = head;
}else{
next = new ListNode(value);
cur.next = next;
cur = next;
}
l2 = l2.next;
}
if(sum > 0){
next = new ListNode(sum);
cur.next = next;
cur = next;
}
return head;
}
Add two numbers
最新推荐文章于 2021-06-02 14:45:00 发布