算法设计与分析课作业【week2】Add Two Numbers

题目

You are given two linked non-empty 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.

题目要求的是将两条数字链相加,返回加完后的正确结果。由于是指针问题,所以在申请新内存方面要多考虑,有以下三个较为重要的情况需要考虑:

  1. 两条链长度不同时,不能忘了长的链后面的数也要加上。
  2. 当加到其中有一条链为空时,还要继续考虑进位的问题。例如:(1->2)+ (1->8->7->6)
  3. 当加到最后有新的进位时,需要再申请内存存数。例如:(1->2)+ (1->8->9->9)

由于题目说明为两条非空链,如果没有说明的话,我们还需要考虑当两条链同时为空或者有一条为空链的情况。

C++代码如下:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* result, *head;
        int carry = 0;
        //首先确定和的头指针
        int tmp = l1->val + l2->val;
        result = new ListNode(tmp % 10);
        head = result;
        carry = tmp / 10;
        l1 = l1->next;
        l2 = l2->next;

        //两条链不为空时一直相加
        while (l1 != NULL && l2 != NULL) {
            int tmp = l1->val + l2->val;
            result->next = new ListNode((tmp + carry) % 10);
            carry = (tmp + carry) / 10;
            result = result->next;
            l1 = l1->next;
            l2 = l2->next;
        }

        /*
          当加到有一条链为空时,结果需要加上另一条链剩下的数,
          同时不能忘了在另一条链为空时,可能存在进位。
        */
        if (l1 == NULL) {
            while (l2 != NULL) {
                result->next = new ListNode((l2->val + carry) % 10);
                carry = (l2->val + carry) / 10;
                result = result->next;
                l2 = l2->next;
            }
        }
        else {
            while (l1 != NULL) {
                result->next = new ListNode((l1->val + carry) % 10);
                carry = (l1->val + carry) / 10;
                result = result->next;
                l1 = l1->next;
            }
        }
        
        //考虑最后是否还有进位,有则申请行内存
        if (carry) {
            result->next = new ListNode(1);
        }
        return head;
    }
};

猜你喜欢

转载自blog.csdn.net/weixin_36332464/article/details/82724762
今日推荐