【LeetCode】【2】【链表】

题目: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.

解题思路:不要被题目中的逆序迷惑了,自己把加法的算式列一下就会发现正好是从头开始算起,注意进位的问题。dummyHead是一个链表中很常用的方法。
代码:

public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode dummyHead = new ListNode(0);
        ListNode curr = dummyHead;
        int carry = 0;      //表示来自上一位的进位
        while (l1!=null || l2!=null){
            int a = l1!=null?l1.val:0;     //用于解决当两个数位数不同时,把高位看成0
            int b = l2!=null?l2.val:0;
            int sum = a+b+carry;
            carry = sum/10;          //算出要传递给下一位的进位
            curr.next = new ListNode(sum%10);     
            curr = curr.next;          //链表移动

            if(l1!=null)l1 = l1.next;         //注意前面的判断,要不然会报错空指针
            if(l2!=null)l2 = l2.next;
        }
        if(carry>1)curr.next = new ListNode(1);          //最高位的进位问题

        return dummyHead.next;

    }

猜你喜欢

转载自blog.csdn.net/u012503241/article/details/82862304