20.12.24 leetcode2

题目链接:https://leetcode-cn.com/problems/add-two-numbers/

题意:给你两个链表,每个链表都表示一个从后往前的十进制数,每个位都只容纳一个数字。

分析:构造一个新链表,每一位都是两个链表的对应位加上进位。

/**
 * 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,tail=null;
        int carry=0;
        while(l1!=null||l2!=null){
            int n1 = l1!=null?l1.val:0;
            int n2 = l2!=null?l2.val:0;
            int sum = (n1+n2+carry)%10;
            if(head==null){
                head=tail= new ListNode(sum);
            }else{
                tail.next=new ListNode(sum);
                tail=tail.next;
            }
            if(l1!=null)l1=l1.next;
            if(l2!=null)l2=l2.next;
            carry=(n1+n2+carry)/10;
        }
        if(carry!=0)tail.next=new ListNode(carry);
        return head;
    }
}
原文地址:https://www.cnblogs.com/qingjiuling/p/14182910.html