Add Two Numbers

来源:互联网 发布:工程施工进度计划软件 编辑:程序博客网 时间:2024/06/05 02:47

今天开始刷LeedCode了.

发现智商不够用了.有些解题方法是Goole来的...

答题语言都是c语言,顺便也是巩固了一下数据结构

原题链接:

点击打开链接

/** * Definition for singly-linked list. * struct ListNode { *     int val; *     struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {        struct ListNode *ret = (struct ListNode *)malloc(sizeof(struct ListNode)), *ltemp, *t;    int cr = 0, var;    ltemp = ret;        while(l1 || l2){        var = ( l1 ? l1->val : 0)+(l2 ? l2->val : 0)+cr;        cr = var/10;        var = var%10;        ltemp->next = (struct ListNode *)malloc(sizeof(struct ListNode));        ltemp->next->val = var; ltemp = ltemp->next;                if(l1)            l1 = l1->next;        if(l2)            l2 = l2->next;    }        if(cr == 1){        ltemp->next = (struct ListNode *)malloc(sizeof(struct ListNode));        ltemp->next->val = cr; ltemp = ltemp->next;    }    ltemp->next = NULL;        t = ret; ret = ret->next; free(t);    return ret;}


原创粉丝点击