/**
* 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) {
ListNode dummy = new ListNode(0);
ListNode itr = dummy;
ListNode p1 = l1, p2 = l2;
boolean hasCarry = false;
while(p1 != null || p2 != null) {
int a1 = p1 == null ? 0 : p1.val;
int a2 = p2 == null ? 0 : p2.val;
int a = hasCarry ? a1 + a2 + 1 : a1 + a2;
hasCarry = a >= 10 ? true : false;
a %= 10;
itr.next = new ListNode(a);
p1 = p1 == null ? null : p1.next;
p2 = p2 == null ? null : p2.next;
itr = itr.next;
}
itr.next = hasCarry ? new ListNode(1) : null;
return dummy.next;
}
}
Time: O(n)
Space: O(1)