Add Two Number

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

   题目大意 ; 324 + 465 = 807 只是用链表表示 并且逆转了;

   题目思路 :

      链表的题目,必然又是许多细节性的问题 ,  每个数的前一位 就是 链表中对应的下一个 , 所以只要遍历两个链表

      逐位相加即可 ; 因为低位在前,所以不要担心 位数不同的情况;

      但是要特别注意 这种情况[1] , [9 , 9 ,9] , 也就是他的进位操作(add1()方法)是递归的!!

public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        ListNode l1It = l1;
        ListNode l2It = l2;
        ListNode head = l1;
        ListNode p = l1;
        if(l1 == null && l2 == null) return null;
        if(l1 == null) return l2;
        if(l2 == null) return l1;
        // 每个数的前一位 就是 链表中对应的下一个
        while(l1It != null && l2It != null) {
            int tmp = l1It.val + l2It.val;
            p = l1;
            if(tmp  < 10) {
                l1.val = tmp;
                l1 = l1.next;
            } else {
                l1.val = tmp - 10;
                l1 = l1.next;
                if(l1 != null) {
                    add1(l1);
                } else if (l2It.next != null) {
                    add1(l2It.next);
                } else {
                    ListNode ln = new ListNode(1);
                    p.next = ln;
                }
            }
            l1It = l1It.next;
            l2It = l2It.next;
        }
       if(l1It == null && l2It == null) return head;
       if(l1It == null) {
           p.next = l2It;
           return head;
       } else if(l2It == null) {
           p.next = l1It;
           return head;
       }
       return null;
    }
    
    public void add1(ListNode ln) {
        if(++ln.val >= 10) {
            ln.val = ln.val - 10;
            if(ln.next == null) {
                ListNode l = new ListNode(1);
                ln.next = l;
            } else {
                add1(ln.next); // 这是一个递归的过程
            }
        }
    }
}

猜你喜欢

转载自kainever7.iteye.com/blog/2207759
今日推荐