[LeetCode] #2 Add Two Numbers

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

本题其实就是两个链表合并,不同的就是要考虑进位。时间:110ms

代码如下:

/**
 * 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) {
        if (l1 == NULL )
            return l2;
        if(l2 == NULL)
            return l1;
        ListNode *l3=NULL, *node;
        ListNode *pHead1 = l1, *pHead2 = l2, *pHead3 = l3;
        int up = 0;
        while (pHead1 != NULL && pHead2 != NULL){
            node = new ListNode(pHead1->val + pHead2->val + up);
            up = node->val / 10;
            node->val = node->val %10;
            if (l3 == NULL){
                l3 = pHead3 = node;
            }
            else{
                pHead3->next = node;
                pHead3 = pHead3->next;
            }
            pHead1 = pHead1->next;
            pHead2 = pHead2->next;
        }
        while (pHead1 != NULL){
            node = new ListNode(pHead1->val + up);
            up = node->val / 10;
            node->val = node->val % 10;
            pHead3->next = node;
            pHead1 = pHead1->next;
            pHead3 = pHead3->next;
        }
        while (pHead2 != NULL){
            node = new ListNode(pHead2->val + up);
            up = node->val / 10;
            node->val = node->val % 10;
            pHead3->next = node;
            pHead2 = pHead2->next;
            pHead3 = pHead3->next;
        }
        if (up > 0){
            node = new ListNode(up);
            pHead3->next = node;
        }
        return l3;
    }
};
“If you give someone a program, you will frustrate them for a day; if you teach them how to program, you will frustrate them for a lifetime.”
原文地址:https://www.cnblogs.com/Scorpio989/p/4394460.html