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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

对两个链表做加法,每个结点的值只能是个位数,向后进位;
对于两个链表不一样长的情况,可以让短的链表后面的值都为0,也可以直接把长的链表多余的部分链接到ans链表的尾。但在本题中,因为要处理进位,如果两个链表分别是[1];[9,9,9,9],结果是[0,0,0,0,1],不能直接把多余的连接到表尾,因此采用第一种处理方式。

class Solution {
public:
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
        ListNode* ans = new ListNode(0);
        ListNode* P = ans;  // P指向结果链表的最后一位
        int count = 0;
        while(l1 || l2){
            if(l1){
                count += l1->val;
                l1 = l1->next;
            }
            if(l2){
                count += l2->val;
                l2 = l2->next;
            }
            P->next = new ListNode(count % 10);
            P = P->next;
            count /= 10;
        }
        if(count) {  // 如果l1,l2都为空,但剩余一个进位,需要新增加结点
            P->next = new ListNode(1);
        }
        return ans->next;
    }
};
posted @ 2017-07-09 20:43  lepeCoder  阅读(168)  评论(0编辑  收藏  举报