Leetcode-Add Two Numbers(Java)

Question:

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

Thinking:

It’s like a problem adding two numbers from the low digits to high digits. We need two variable to record the sum of current digit and whether it will incresce the next digit. Then what we should care about is to traverse the linked list and check whether it’s null pointer.

Solution:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
    int num1 = 0;
    int num2 = 0;
    int sum = 0;
    int flag = 0;

    if (l1 != null){
        num1 = l1.val;
        l1 = l1.next;
    }
    if (l2 != null){
        num2 = l2.val;
        l2 = l2.next;
    }
    sum = (num1 + num2) % 10;
    flag = (num1 + num2) / 10;
    ListNode head = new ListNode(sum);
    ListNode p = head;

    while (l1 != null || l2 != null){
        num1 = 0;
        num2 = 0;
        if (l1 != null) {
            num1 = l1.val;
            l1 = l1.next;
        }
        if (l2 != null) {
            num2 = l2.val;
            l2 = l2.next;
        }

        sum = (num1 + num2 + flag) % 10;
        flag = (num1 + num2 + flag) / 10;
        p.next = new ListNode(sum);
        p = p.next;
    }

    if (flag == 1)
        p.next = new ListNode(1);

    return head;
}