题目:
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
使用什么语言实现思路都近似,此处用java实现。

/**
 * 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) {
        if(l1 == null && l2 == null)
        {
            return null;
        }
        ListNode lhead;
        ListNode l = new ListNode(0);
        lhead = l;//用于保存最初位置
        int flag=0;
        while(l1!=null || l2!=null)
        {
            ListNode lnext = new ListNode(0);//每次运算保存于新添加的节点并接在后面
            int a = l1==null?0:l1.val;
            int b = l2==null?0:l2.val;
            lnext.val = (a+b+flag)%10;
            flag = (a+b+flag)/10;
            l.next = lnext;
            l = l.next;
            l1 = l1==null?null:l1.next;
            l2 = l2==null?null:l2.next;
        }
        if(flag != 0)    //如果还有进位,添加节点存入其中
        {
            ListNode lnext = new ListNode(0);
            lnext.val = flag;
            l.next = lnext;
            lnext.next = null;
        }
        return lhead.next;
    }
}
Logo

开放原子开发者工作坊旨在鼓励更多人参与开源活动,与志同道合的开发者们相互交流开发经验、分享开发心得、获取前沿技术趋势。工作坊有多种形式的开发者活动,如meetup、训练营等,主打技术交流,干货满满,真诚地邀请各位开发者共同参与!

更多推荐