LeetCode -- Add Two Numbers

Question:

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

Analysis:

给出两个由非负整数构成的链表。数字倒序存放在链表中,对两个数相加然后返回倒序的和。例如题目中给出的例子的意思是:342+465 = 807.

刚开始做时发现,243 + 564 = 807,因此以为正序加与反序加效果一样,但后来有很多情况并不适用。

解题思路:首先对两个两边进行就地转置,然后将表示的数字相加(用long型保存);然后对和反序保存并返回。

Answer:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        long lo1 = 0, lo2 = 0;
        ListNode h1 = reverseList(l1), h2 = reverseList(l2);
        while(h1 != null) {
            lo1 = lo1 * 10 + h1.val;
            h1 = h1.next;
        }
        while(h2 != null) {
            lo2 = lo2 * 10 + h2.val;
            h2 = h2.next;
        }
        long sum = lo1 + lo2;
        ListNode head = new ListNode(0);
        h1 = head;
        if(sum == 0) {
            return head;
        }
        while(sum != 0) {
            int val = (int) (sum % 10);
            ListNode li = new ListNode(val);
            sum = sum / 10;
            h1.next = li;
            h1 = li;
        }
        
        return head.next;
    }
    
    public ListNode reverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode h = head;
        while(head.next != null) {
            ListNode p = head.next;
            head.next = p.next;
            p.next = h;
            h = p;
        }
        return h;
    }
}
原文地址:https://www.cnblogs.com/little-YTMM/p/4796008.html