LeetCode-2:Add Two Numbers (两链表数相加)

这个问题太简单了,直接上代码

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(0);
        int inc = 0;
        ListNode cur1 = l1;
        ListNode cur2 = l2;
        ListNode cur = result;
        while (cur1 != null && cur2 != null){
            int r = cur1.val + cur2.val + inc;
            inc = r/10;
            r %= 10;
            cur.next = new ListNode(r);
            cur = cur.next;
            cur1 = cur1.next;
            cur2 = cur2.next;
        }
        //结束了,判定到底是谁计算完了
        ListNode tempCur = null;
        if (cur1 != null){
            tempCur = cur1;
        } else if (cur2 != null){
            tempCur = cur2;
        }
        while (tempCur != null){
            int r = tempCur.val + inc;
            inc = r/10;
            r %= 10;
            cur.next = new ListNode(r);
            cur = cur.next;
            tempCur = tempCur.next;
        }
        if (inc > 0){
            cur.next = new ListNode(inc);
        }
        return result.next;
    }
}

 

posted @ 2019-01-10 15:32  ronghantao  阅读(136)  评论(0编辑  收藏  举报