Leetcode 2. Add Two Numbers

题目:
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

思路:按位相加,本为的两个数和前一个位置的进位carry。相加结果分为两部分,一部分,本位最终数值,一部分,进位的值carry。

代码:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode list = new ListNode(0);
        list.next = null;
        ListNode phead = list;
        int carry = 0;
        int num1 = 0;
        int num2 = 0;
        while(l1 != null || l2 != null){
            if(l1 == null){
                num1 = 0;
            }else{
                num1 = l1.val;
                l1 = l1.next;
            }

            if(l2 == null){
                num2 = 0;
            }else{
                num2 = l2.val;
                l2 = l2.next;
            }
            int temp = num1 + num2 + carry;
            carry = temp / 10;
            ListNode p = new ListNode(temp % 10);
            p.next = null;
            phead.next = p;
            phead = p;
        }
        if(carry != 0){
            ListNode last = new ListNode(carry);
            phead.next = last;
            last.next = null;
        }
        return list.next;
    }

你可能感兴趣的:(LeetCode,链表,linklist)