【LeetCode】2、Add Two Numbers

题目等级:Medium

题目描述:

  You are given two non-empty linked lists representing two non-negative integers. 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.

  You may assume the two numbers do not contain any leading zero, except the number 0 itself.

  Example:

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

  题意:给定两个链表,每个链表代表一个整数,但是是逆序存储的,求两个链表代表的数的和,结果仍然逆序保存在链表中。


解题思路:

  本题实际上也比较简单,两个链表逆序存储,相当于从最低位开始,根据加法运算,只需要把低位相加,然后将进位传递为高位,高位加的时候多考虑一个进位就可以了,很好理解。

  具体过程直接看下面的代码:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        if(l1==null)
            return l2;
        if(l2==null)
            return l1;
        ListNode head=new ListNode(-1);
        ListNode cur=head;
        int carry=0;  //进位
        while(l1!=null || l2!=null){
            int num1=l1==null?0:l1.val;
            int num2=l2==null?0:l2.val;
            int sum=num1+num2+carry; //低位依次相加
            carry=sum/10;
            
            ListNode temp=new ListNode(sum%10);
            temp.next=null;
            cur.next=temp;
            cur=temp;
            if(l1!=null)   l1=l1.next;
            if(l2!=null)   l2=l2.next;
        }
        if(carry!=0){ //最后是否还有一位进位,要注意判断,比如:5+5
            cur.next=new ListNode(carry);
            cur.next.next=null;
        }
        return head.next;
    }
}

  扩展:

  What if the the digits in the linked list are stored in non-reversed order? For example:

  (3→4→2)+(4→6→5)=8→0→7

  本题最后给出了一个扩展,当链表的数不是逆序存储,而是从高位到低位正序存储时,该怎么办?

  很明显,最直观的想法就是不是逆序就先将链表进行反转,变为逆序,然后再利用本题的思路解决。那么这里的关键问题就是如何反转链表?

  实际上,反转链表这道题目在多个地方出现,可以使用三指针或者递归的解法,具体可以参考另外一篇博客:【剑指Offer】15、反转链表

原文地址:https://www.cnblogs.com/gzshan/p/10955313.html