LeetCode 2. Add Two Numbers

来源:互联网 发布:淘宝加盟骗局 编辑:程序博客网 时间:2024/06/11 15:24



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.

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



题目大意是通过链表把数字加起来,其中还有进位。
第一次提交直接WA了,因为有个数据是[5]+[5],输出应该是[0,1],也就是5+5=10,一开始没考虑到。。。
下面是我用c++语言写的代码,比较拙劣。

/** * 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 carry = 0;        ListNode* ans = (ListNode*)malloc(sizeof(ListNode));        *ans = ListNode(-1);        ListNode* res = ans;        ListNode* temp = (ListNode*)malloc(sizeof(ListNode));        *temp = ListNode(0);        while(l1!=NULL&&l2!=NULL){            temp->val = carry;            carry = 0;            temp->val += l1->val;            temp->val += l2->val;            l1 = l1->next;            l2 = l2->next;            carry = temp->val/10;            temp->val = temp->val%10;            if(ans->val!=-1){                ans->next = (ListNode*)malloc(sizeof(ListNode));                ans = ans->next;                *ans = ListNode(temp->val);            }            else{                *ans = ListNode(temp->val);            }        }        if(l1==NULL){            while (l2!=NULL) {                temp->val = carry;                carry = 0;                temp->val += l2->val;                l2 = l2->next;                carry = temp->val/10;                temp->val = temp->val%10;                if(ans->val!=-1){                    ans->next = (ListNode*)malloc(sizeof(ListNode));                    ans = ans->next;                    *ans = ListNode(temp->val);                }                else{                    *ans = ListNode(temp->val);                }            }        }else{            while (l1!=NULL) {                temp->val = carry;                carry = 0;                temp->val += l1->val;                l1 = l1->next;                carry = temp->val/10;                temp->val = temp->val%10;                if(ans->val!=-1){                    ans->next = (ListNode*)malloc(sizeof(ListNode));                    ans = ans->next;                    *ans = ListNode(temp->val);                }                else{                    *ans = ListNode(temp->val);                }            }        }        if(l1==NULL&&l2==NULL&&carry!=0){             ans->next = (ListNode*)malloc(sizeof(ListNode));             ans = ans->next;             *ans = ListNode(carry);        }        return res;    }};