Leetcode 2 两数相加

题目地址:https://leetcode-cn.com/problems/add-two-numbers/

难度:简单

基本思路:

  • 大于10要考虑进位,具体进几位用整除,当前结点大小用模除
  • 要考虑两条链表不一样长度的情况,所以遍历的判断条件是有一个不为空则继续,二者皆空则停止
class Solution {
    // 与官方题解思路一致, 效率低是因为多创建了结点
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode head = null, res = null;
        int carry = 0, val, l1Val, l2Val, sum;
        while(l1 != null || l2 != null){
            l1Val = l1 == null ? 0 : l1.val;
            l2Val = l2 == null ? 0 : l2.val;
            sum = l1Val + l2Val + carry;
            val = sum % 10;
            carry = sum / 10;
            if(head == null){
                res = head = new ListNode(val);
            }else{
                res.next = new ListNode(val);
                res = res.next;
            }
            if(l1 != null){
                l1 = l1.next;
            }
            if(l2 != null){
                l2 = l2.next;
            }
            if(carry > 0){
                res.next = new ListNode(carry);
            }
        }
        return head;
    }
}

 

posted @ 2021-04-12 13:13  YC-L  阅读(6)  评论(0编辑  收藏