2. 两数相加 + 模拟加法 + 链表

2. 两数相加

LeetCode_2

类似题目:415. 字符串相加

题目描述

代码实现

/**
 * 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 = null;
        ListNode now = null;
        int carr = 0;
        while(l1 != null || l2 != null){
            int first = l1 != null ? l1.val : 0;
            int right = l2 != null ? l2.val : 0;
            int total = first + right + carr;
            if(head == null){
                head = now = new ListNode(total % 10);
            }else{
                now.next = new ListNode(total % 10);
                now = now.next;
            }
            if(l1 != null)
                l1 = l1.next;
            if(l2 != null)
                l2 = l2.next;
            carr = total / 10;
        }
        if(carr > 0)
            now.next = new ListNode(carr);
        return head;
    }
}
posted @ 2021-03-18 11:17  Garrett_Wale  阅读(37)  评论(0编辑  收藏  举报