【大数相加链表模拟】

发布时间 2023-12-14 17:23:16作者: 沙汀鱼

leetcode 2. 两数相加

题意:两个长度为[1, 100]的大数,分别倒序存储(个位在链表头)在两个链表中,计算两个数的和,并倒序存储在一个新链表,返回链表表头。数据中不存在前导零。

题解:模拟大数相加,注意维护进位carry即可

代码
/**
 * 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 head, tail;
        head = tail = null;
        int carry = 0;
        while(l1 != null || l2 != null) {
            int val1 = 0, val2 = 0;
            if(l1 != null) val1 = l1.val;
            if(l2 != null) val2 = l2.val;
            int sum = val1 + val2 + carry;
            if(sum >= 10) {carry = 1; sum %= 10;}
            else carry = 0;
            if(head == null) {
                head = tail = new ListNode(sum, null);
            } else {
                tail.next = new ListNode(sum, null);
                tail = tail.next;
            }
            if(carry == 1) tail.next = new ListNode(carry, null);
            if(l1 != null) l1 = l1.next;
            if(l2 != null) l2 = l2.next;
        }
        return head;
    }
}