LeetCode - 2. 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.

Example:

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

思路:

    题目的意思很明确,就是相加,进位,相加,进位,不过需要注意的就是最后可能多出一位。这种链表的题,一般都是先弄个dummyHead,用来存放头,然后用一个指针,一位一位往后走,在dummyHead后边new出来新的,然后赋值,最后返回dummyHead->next。AC代码如下:

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
    ListNode* dummyHead = new ListNode(-1);
    dummyHead->next = new ListNode(0);
    ListNode* res = dummyHead;
    int carry = 0;  // 进位
    while(l1 || l2)
    {
        int tmp_sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + carry;
        res->next = new ListNode(tmp_sum % 10);
        res = res->next;
        carry = tmp_sum / 10;
        if(l1)
            l1 = l1->next;
        if(l2)
            l2 = l2->next;        
    }
    if(carry != 0)
        res->next = new ListNode(carry);
    return dummyHead->next;
}

猜你喜欢

转载自blog.csdn.net/Bob__yuan/article/details/81407946
今日推荐