Add Two Numbers

来源:互联网 发布:塑料高跟鞋淘宝 编辑:程序博客网 时间:2024/04/29 21:43

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


/** * 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) {        int c = 0;        ListNode *head = NULL;        ListNode *prev = NULL;        ListNode *p = NULL;        while (l1 || l2)        {            int temp = c;            if (l1)            {                temp += l1->val;            }            if (l2)            {                temp += l2->val;            }            int val = temp%10;            c = temp / 10;            if (head == NULL)            {                head = new ListNode(val);                prev = head;            }            else            {                p = new ListNode(val);                prev->next = p;                prev = p;            }            if (l1)            {                l1 = l1->next;            }            if (l2)            {                l2 = l2->next;            }        }        if (c)        {            p = new ListNode(c);            prev->next = p;            prev = p;        }        prev->next = NULL;            return head;    }};


0 0