2.两数相加

/**
 * 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) {
        ListNode res = new ListNode();
        ListNode head = res;
        int carry = 0;
        while(l1 != null || l2 != null){
            int num1 = 0, num2 = 0;
            if(l1 != null){
                num1 = l1.val;
                l1 = l1.next;
            }
            if(l2 != null){
                num2 = l2.val;
                l2 = l2.next;
            }
            int sum = num1 + num2 + carry;
            if (sum < 10) {
                carry = 0;
            } else {
                sum -= 10;
                carry = 1;
            }
            res.next = new ListNode(sum);
            res = res.next;
        }

        if(carry != 0)
        res.next = new ListNode(1);

        return head.next;
    }
}

https://leetcode-cn.com/problems/add-two-numbers/

上一篇:力扣-4.寻找两个正序数组的中位数


下一篇:两个长度相同有序序列的中位数