二刷2. Add Two Numbers

Medium
L面经题,几百年没刷LinkedList的题了,这道题处理小细节也提交了好几次,其实是道很简单的题

/**
 * 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 dummy = new ListNode(0);
        ListNode curt = dummy;
        int carry = 0;
        ListNode curt1 = l1;
        ListNode curt2 = l2;
        int sum = 0;
        while (curt1 != null && curt2 != null){
            sum = curt1.val + curt2.val + carry;
            carry = 0;
            if (sum >= 10){
                carry++;
                sum %= 10;
            }
            curt.next = new ListNode(sum);
            curt = curt.next;
            curt1 = curt1.next;
            curt2 = curt2.next;
            sum = 0;
        }
        while (curt1 != null){
            sum = curt1.val + carry;
            carry = 0;
            if (sum >= 10){
                carry++;
                sum %= 10;
            }
            curt.next = new ListNode(sum);
            curt = curt.next;
            curt1 = curt1.next;
            sum = 0;
        }
        while (curt2 != null){
            sum = curt2.val + carry;
            carry = 0;
            if (sum >= 10){
                carry++;
                sum %= 10;
            }
            curt.next = new ListNode(sum);
            curt = curt.next;
            curt2 = curt2.next;
            sum = 0;
        }
        if (carry != 0){
            curt.next = new ListNode(carry);
        }
        return dummy.next;
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/677ae152382a
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞