Loading

LeetCode 2. 两数相加

image

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;

        ListNode l3 = new ListNode();
        ListNode p1 = l1, p2 = l2, p3 = l3;
        int carry = 0;
        while(true) {
            if (p1 == null && p2 == null) break;

            int a = p1 == null ? 0 : p1.val;
            int b = p2 == null ? 0 : p2.val;
            int sum = a + b + carry;
            if (sum >= 10) {
                carry = 1;
                sum -= 10;
            } else {
                carry = 0;
            }

            p3.next = new ListNode(sum);

            if (p1 != null) {
                p1 = p1.next;
            } 

            if (p2 != null) {
                p2 = p2.next;
            } 
            
            p3 = p3.next;
        }

        if(carry == 1) {
            p3.next = new ListNode(1);
        } 

        return l3.next;
    }
}
posted @ 2022-05-27 11:30  拾月凄辰  阅读(19)  评论(0编辑  收藏  举报