链表 两数之和

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.


public class AddTwoSum{
    public ListNode addTwoNumbers(ListNode l1,ListNode l2){
        ListNode dummyHead = new ListNode(0);
        ListNode p = l1,q = l2,cur = dummyHead;
        int carry = 0;
        while(p!=null || q!=null){
            int x = (p != null) ? p.val : 0;
                int y = (q != null) ? q.val : 0;
            int sum = carry + x + y;
            cur.next = new ListNode(sum % 10);
            cur = cur.next;
            carry = sum/10;
            if(p != null)
                p = p.next;
            if(q != null)
                q = q.next;
        }
        if(carry > 0)
            cur.next =new ListNode(carry);
        return dummyHead.next;
    }
}

题目说,给出两个链表,链表中分别存储着逆序的正整数,将这两个整数相加并且同样的输出逆序的链表。首先观察规律,我们在对两个数做加法时,总是从最低位加起的,那么只要按顺序将每条链表的头部值相加,放到链表中,就可以得到该位的值,要考虑到进位,定义一个int类型carry,carry只能为0或者1,在下次计算的时候再随着两条链表的下个结点一起加进去就是了。

猜你喜欢

转载自www.cnblogs.com/tiandiou/p/9699755.html