You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = l1;
int add = 0;
ListNode p1 = null;
ListNode p2 = null;
boolean flag = false;
while(l1 != null || l2 != null) {
int temp = 0;
if(l1 != null) {
temp += l1.val;
p1 = l1;
l1 = l1.next;
} else if(!flag){
flag = true;
p1.next = l2;
}
if(l2 != null) {
temp += l2.val;
p2 = l2;
l2 = l2.next;
}
temp += add;
if(!flag) {
p1.val = temp % 10;
} else {
p2.val = temp % 10;
}
add = temp / 10;
}
if(add == 1) {
ListNode end = new ListNode(1);
end.next = null;
if(flag) {
p2.next = end;
} else {
p1.next = end;
}
}
return head;
}
}
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode c1 = l1;
ListNode c2 = l2;
ListNode sentinel = new ListNode(0);
ListNode d = sentinel;
int sum = 0;
while (c1 != null || c2 != null) {
sum /= 10;
if (c1 != null) {
sum += c1.val;
c1 = c1.next;
}
if (c2 != null) {
sum += c2.val;
c2 = c2.next;
}
d.next = new ListNode(sum % 10);
d = d.next;
}
if (sum / 10 == 1)
d.next = new ListNode(1);
return sentinel.next;
}
}
网友评论