力扣2:两数相加

 力扣(LeetCode)官网 - 全球极客挚爱的技术成长平台

/**
 * 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) {
        int total = 0;//相加的结果
        int next1 = 0;//向后进的一位
        ListNode result = new ListNode();
        ListNode cur = result;
        while (l1 != null && l2 != null) {
            total = l1.val + l2.val + next1;
            cur.next = new ListNode(total % 10);
            next1 = total / 10;
            l1 = l1.next;
            l2 = l2.next;
            cur = cur.next;
        }

        while (l1 != null) {
            total = l1.val + next1;
            cur.next =new ListNode(total % 10);
            next1 = total / 10;
            l1 = l1.next;
            cur = cur.next;
        }
        while (l2 != null) {
            total = l2.val + next1;
            cur.next =new ListNode(total % 10);
            next1 = total / 10;
            l2 = l2.next;
            cur = cur.next;
        }

        if(next1!=0){
            cur.next = new ListNode(next1);
        }
        return result.next;
    }
}

你可能感兴趣的:(leetcode,算法,职场和发展)