Add Two Numbers

来源:互联网 发布:sql删除表数据语句 编辑:程序博客网 时间:2024/06/06 15:38

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.

/** * 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) {        ListNode headNode(INT_MAX);        ListNode* head = &headNode;        int carry = 0;        while(l1 || l2)        {            int val1 = l1?l1->val:0;            int val2 = l2?l2->val:0;            int tmp = val1+val2+carry;            head->next = new ListNode(tmp%10);            carry = tmp/10;            head = head->next;            if(l1)                l1 = l1->next;            if(l2)                l2 = l2->next;        }        if(carry!=0)        {            head->next = new ListNode(carry);            }        return headNode.next;    }};
0 0
原创粉丝点击