Leetcode Add Two numbers 题目解析(java实现)

2. Leetcode Add Two numbers 题目解析(java实现)

题目描述
时间复杂度O(max(m,n)),首先根据链表长度区分三种情况,l1和l2同时遍历到空,l1先为空,l2先为空。注释部分的ListNode类需提前声明,建立一个新链表,然后把输入的两个链表从头往后撸,每两个相加,添加一个新节点到新链表后面,注意的就是要处理下进位(carry变量)问题。

第一种方法:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode result = new ListNode(-1);
        ListNode cur = result;
        int carry = 0;
        while(l1!=null&&l2!=null){
            int d1 = l1.val;
            int d2 = l2.val;
            int sum = d1 + d2 +carry;
            carry = sum >=10 ?1:0;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            if (l1 != null) l1 = l1.next;
            if (l2 != null) l2 = l2.next; 
            if (carry ==1){
            cur.next = new ListNode(1);
            }    
        }while(l1!=null&&l2==null){
            int d1 = l1.val;
            int sum = d1 +carry;
            carry = sum >=10 ?1:0;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            if (l1 != null) l1 = l1.next;
            if (carry ==1){
            cur.next = new ListNode(1);
            }    
        }while(l1==null &&l2!=null){
            int d2 = l2.val;
            int sum = d2 +carry;
            carry = sum >=10 ?1:0;
            cur.next = new ListNode(sum%10);
            cur = cur.next;
            if (l2 != null) l2 = l2.next;
            if (carry ==1){
            cur.next = new ListNode(1);
            }    
        }
       
        return result.next;
    
    }
}

你可能感兴趣的:(Leetcode Add Two numbers 题目解析(java实现))