Add Two Numbers

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.

Your input {1,2,8} {1,8,1}

Your answer{2,0,0,1}

一道链表题 需要注意点的有三个

第一: 正常的进位问题(包括上一步运算的进位1 加上这次运算的结果又有进位)

第二: 如果两个链表不一样长,如何不在判断和向下传输的过程不返回空指针异常

第三: 最后一位运算时如果有进位怎么办;

/**

* 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) {

        ListNode resultList = new ListNode(0);

        ListNode temp = resultList;

        ListNode mSum = new ListNode(0);

        while(l1 != null || l2 != null){

            int list1 = (l1 != null) ? l1.val : 0;

            int list2 = (l2 != null) ? l2.val : 0;

            int sum = list1 + list2;

            int dSum = (sum + mSum.val) % 10;

            //int input = (dSum + mSum.val) % 10;

            temp = temp.next = new ListNode(dSum);

            mSum = mSum.next = new ListNode((sum + mSum.val) / 10);

            l1 = (l1 == null) ? null : l1.next;

            l2 = (l2 == null) ? null : l2.next;

        }

        if(mSum.val == 1){

            temp.next = new ListNode(1);

        }

        return resultList.next;

    }

}

你可能感兴趣的:(Add Two Numbers)