题解 | #链表相加(一)#

链表相加(一)

http://www.nowcoder.com/practice/521d83306d964c1188639033eb59621d

/**
 * struct ListNode {
 *	int val;
 *	struct ListNode *next;
 * };
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 *
 * C语言声明定义全局变量请加上static,防止重复定义
 */
/**
 * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
 *
 * 
 * @param l1 ListNode类 
 * @param l2 ListNode类 
 * @return ListNode类
 */
struct ListNode* ListAdd(struct ListNode* l1, struct ListNode* l2 ) {
    // write code here
    int sum = 0;
    int carry = 0;
    int val1 = 0;
    int val2 = 0;
    struct ListNode* lResult = NULL;
    struct ListNode* lReturn = NULL;
    struct ListNode* lTemp = NULL;
    
    while (l1 || l2 || carry == 1) {
        val1 = (l1 == NULL ? 0 : l1->val);
        val2 = (l2 == NULL ? 0 : l2->val);
        sum = val1 + val2 + carry;
        carry = sum / 10;
        sum = sum % 10;
        lTemp = (struct ListNode*)malloc(sizeof(struct ListNode));
        lTemp->next = NULL;
        lTemp->val = sum;
        if (lResult == NULL) {
            lResult = lTemp;
            lReturn = lResult;
        }
        lResult->next = lTemp;
        lResult = lResult->next;
        l1 = (l1 == NULL)? NULL : l1->next;
        l2 = (l2 == NULL)? NULL : l2->next;
    }
    /*if (carry == 1) {
        lTemp = (struct ListNode*)malloc(sizeof(struct ListNode));
        lTemp->next = NULL;
        lTemp->val = carry;
        lResult->next = lTemp;
        lResult = lResult->next;
    }*/
    return lReturn;
}
全部评论

相关推荐

10-15 16:27
门头沟学院 C++
LeoMoon:建议问一下是不是你给他付钱😅😅
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务