2. Add Two Numbers

来源:互联网 发布:北京ios程序员工资待遇 编辑:程序博客网 时间:2024/06/06 02:31

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

思路:直接以l1作为输出队列,将l2上的元素累加的l1上,并记录递增量tmp;

ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {    if (l1 == NULL)return l2;    if (l2 == NULL)return l1;    ListNode* p1 = l1, *p2 = l2;    ListNode *pre1 = NULL, *pre2 = NULL;    int tmp = 0;    while (p1 && p2){        int tt = p1->val + tmp + p2->val;        p1->val = tt % 10;        tmp = tt / 10;        pre1 = p1, pre2 = p2;        p1 = p1->next, p2 = p2->next;    }    if (p1){        while (p1){            int tt = p1->val + tmp;            p1->val = tt % 10;            tmp = tt / 10;            pre1 = p1;            p1 = p1->next;        }    }    if (p2){        pre1->next = p2;        while (p2){            int tt = p2->val + tmp;            p2->val = tt % 10;            tmp = tt / 10;            pre1 = p2;            p2 = p2->next;        }    }    if (tmp){        pre1->next = new ListNode(tmp);    }    return l1;}