首页 > 其他分享 >leetcode2-两数相加

leetcode2-两数相加

时间:2022-08-14 19:00:06浏览次数:105  
标签:leetcode2 相加 next tail l2 l1 null sum 两数

两数相加

  • 循环,每次相加都new一个新的节点
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, tail = null;
        int sum = 0;
        while(l1 != null || l2 != null){
            int n1 = l1 != null ? l1.val : 0;
            int n2 = l2 != null ? l2.val : 0;
            sum = n1+n2+sum/10;
            if(head == null){
                head = tail = new ListNode(sum % 10);
            }else{
                tail.next = new ListNode(sum % 10);
                tail = tail.next;
            }
            if(l1 != null)  l1 = l1.next;
            if(l2 != null)  l2 = l2.next;
        }
        if(sum >= 10){
            tail.next = new ListNode(1);
        }
        return head;
    }
}
  • 使用原有节点
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int sum = 0;
        ListNode head = null, tail = null;
        while(l1 != null){
            int n1 = l1.val;
            int n2 = l2 != null ? l2.val : 0;
            sum = n1+n2+sum/10;
            l1.val = sum % 10;
            if(head == null){
                head = tail = l1;
            }else{
                tail.next = l1;
                tail = tail.next;
            }
            l1 = l1.next;
            if(l2 != null)  l2 = l2.next;
        }
        while(l2 != null){
            sum = l2.val + sum / 10;
            l2.val = sum % 10;
            if(head == null){
                head = tail = l2;
                break;
            }else{
                tail.next = l2;
                tail = tail.next;
            }
            l2 = l2.next;
        }
        if(sum >= 10){
            tail.next = new ListNode(1);
        }
        return head;
    }
}

标签:leetcode2,相加,next,tail,l2,l1,null,sum,两数
From: https://www.cnblogs.com/xzh-yyds/p/16586053.html

相关文章