add-two-numbers-ii

老子叫甜甜 提交于 2020-03-22 22:18:40

注意:有一种好的方法,是将链表倒转,然后依次相加。

但是,按照题目要求,用了不改变原链表的方法。

就是将两个链表增加到相同长度,然后递归相加,子函数返回后处理进位。

https://leetcode.com/problems/add-two-numbers-ii/

package com.company;

import java.util.*;

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}
class Solution {

    ListNode addTwo(ListNode l1, ListNode l2) {
        //System.out.printf("add two %d, %d \n", l1.val, l2.val);
        ListNode ret = new ListNode(l1.val + l2.val);
        if (l1.next != null && l2.next != null) {
            ret.next = addTwo(l1.next, l2.next);
            ret.val += ret.next.val / 10;
            ret.next.val = ret.next.val % 10;
        }
        else {
            ret.next = null;
        }
        return ret;
    }

    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        int l1len = 0;
        ListNode ln = l1;
        while (ln != null) {
            l1len++;
            ln = ln.next;
        }
        int l2len = 0;
        ln = l2;
        while (ln != null) {
            l2len++;
            ln = ln.next;
        }
        if (l1len < l2len) {
            ln = l1;
            l1 = l2;
            l2 = ln;
            l1len = l1len ^ l2len;
            l2len = l1len ^ l2len;
            l1len = l1len ^ l2len;
        }

        for (int i=0; i<l1len-l2len; i++) {
            ln = new ListNode(0);
            ln.next = l2;
            l2 = ln;
        }

        ln = addTwo(l1, l2);
        if (ln.val >= 10) {
            ListNode newHead = new ListNode(ln.val / 10);
            ln.val = ln.val % 10;
            newHead.next = ln;
            ln = newHead;
        }
        return ln;
    }
}

public class Main {

    public static void main(String[] args) {
        System.out.println("Hello!");
        Solution solution = new Solution();

        ListNode l1 = new ListNode(7);
        ListNode l11 = new ListNode(2);
        ListNode l12 = new ListNode(4);
        ListNode l13 = new ListNode(3);
        l1.next = l11;
        l11.next = l12;
        l12.next = l13;
        ListNode l2 = new ListNode(5);
        ListNode l21 = new ListNode(6);
        ListNode l22 = new ListNode(4);
        l2.next = l21;
        l21.next = l22;
        ListNode ret = solution.addTwoNumbers(l1, l2);
        System.out.printf("Get ret: \n");
        while (ret != null) {
            System.out.printf("%d", ret.val);
            ret = ret.next;
        }
        System.out.println();

        /*Iterator<List<Integer>> iterator = ret.iterator();
        while (iterator.hasNext()) {
            Iterator iter = iterator.next().iterator();
            while (iter.hasNext()) {
                System.out.printf("%d,", iter.next());
            }
            System.out.println();
        }*/

        System.out.println();

    }
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!