题目

You are given two linked lists representing two non-negative numbers. 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.
你得到两个链表,表示两个非负数。这些数字以相反的顺序存储,每个节点都包含一个数字。将两个数字相加,并将其作为链表返回。

输入输出
  • Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
  • Output: 7 -> 0 -> 8
思路

其实不用考虑别的,就是两个数字相加,和传统加法唯一的不同就是此题中的加法是从左往右算的,进位也是从左往右进。

例子里给的就是

      2  4  3

+    5  6  4

    ——————————

      7  0  8

正常加法应该先算3+4, 接着4+6,进一位,最后2+5,加之前的进位1,得到8;

在本题就应该先算 2+5, 接着4+6,进一位到3+4中,3+4+1=8,最后得到708。

对于两个list不等长的情况,就把短的list的末尾用0补齐就行了。

所以我直接遍历两个链表了,取出来的数相加放到新表里。当l1.next或者l2.next == null了,用0替代l1.val或l2.val。

最后还要注意当两个链表都遍历完,相加完之后,如果还有进位,要把进位的数字放到新list的末尾。比如 5 + 5 = 0->1


class Solution {
public:
    ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
    
        if(l1 == NULL || l2 == NULL) return (l1 == NULL) ? l2 : l1;
        ListNode* p1 = l1;
        ListNode* p2 = l2;
        int carry = 0,num;//进位,和
        ListNode* res = new ListNode(-1);//头结点
        ListNode* p = res;
        while(p1 != NULL || p2 != NULL || carry) {
            num = (p1 ? p1->val : 0) + (p2 ? p2->val : 0) + carry;
            carry = num >= 10 ? 1 : 0;
            num %= 10;
            ListNode* tmp = new ListNode(num);
            p->next = tmp;
            p = p->next;
            if(p1) p1 = p1->next;
            if(p2) p2 = p2->next;
        }
        return res->next;
    }
};

}; 
结语

初始走在通往IT的道路上,虽然充满荆棘,但是只要能干倒这些荆棘,相信明天一定更美好!

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐