【Lintcode】221. Add Two Numbers II

题目地址:

https://www.lintcode.com/problem/add-two-numbers-ii/description

给定两个链表,其表示一个数的十进制表示,从高位到低位。求其和并返回相同格式的链表。可以先翻转两个链表,再模拟整数相加,再翻转回来即可。代码如下:

public class Solution {
    /**
     * @param l1: The first list.
     * @param l2: The second list.
     * @return: the sum list of l1 and l2.
     */
    public ListNode addLists2(ListNode l1, ListNode l2) {
        // write your code here
        return reverse(add(reverse(l1), reverse(l2)));
    }
    
    private ListNode add(ListNode l1, ListNode l2) {
        int cur = 0;
        ListNode dummy = new ListNode(0), prev = dummy;
        while (l1 != null || l2 != null) {
            if (l1 != null) {
                cur += l1.val;
                l1 = l1.next;
            }
            if (l2 != null) {
                cur += l2.val;
                l2 = l2.next;
            }
            prev.next = new ListNode(cur % 10);
            prev = prev.next;
            cur /= 10;
        }
        
        prev.next = cur == 1 ? new ListNode(1) : null;
        
        return dummy.next;
    }
    
    private ListNode reverse(ListNode head) {
        ListNode res = null;
        while (head != null) {
            ListNode tmp = head.next;
            head.next = res;
            res = head;
            head = tmp;
        }
        return res;
    }
}

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

时间复杂度 O ( n ) O(n) ,空间 O ( 1 ) O(1)

发布了392 篇原创文章 · 获赞 0 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_46105170/article/details/105469363