登录
  • #刷题

请教一道题

chekie
773
5
刚开始刷题。第二题addTwoNumbers。单独test case都没问题,就是提交的时候run time error. last executed input:

[1,1,0,4,7,2,7,3,0,1][2,5,5,6,8,0,3,0,5,1]









我的code(c):

/**[br][/br][br][/br] * Definition for singly-linked list.[br][/br][br][/br] * struct ListNode {[br][/br][br][/br] *     int val;[br][/br][br][/br] *     struct ListNode *next;[br][/br][br][/br] * };[br][/br][br][/br] */[br][/br][br][/br]struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {[br][/br][br][/br]    struct ListNode *result = NULL, *iter, *node;[br][/br][br][/br]    int carry = 0, sum, op1, op2;[br][/br][br][/br]    while (l1 != NULL || l2 != NULL) {[br][/br][br][/br]        if (l1 != NULL) {[br][/br][br][/br]            op1 = l1->val;[br][/br][br][/br]            l1 = l1->next;[br][/br][br][/br]        }[br][/br][br][/br]        else {[br][/br][br][/br]            op1 = 0;[br][/br][br][/br]        }[br][/br][br][/br]        if (l2 != NULL) {[br][/br][br][/br]            op2 = l2->val;[br][/br][br][/br]            l2 = l2->next;[br][/br][br][/br]        }[br][/br][br][/br]        else {[br][/br][br][/br]            op2 = 0;[br][/br][br][/br]        }[br][/br][br][/br]        sum = (op1 + op2 + carry)%10;[br][/br][br][/br]        carry = (op1 + op2 + carry)/10;[br][/br][br][/br]        node = (struct ListNode *)malloc(sizeof(struct ListNode));[br][/br][br][/br]        node->val = sum;[br][/br][br][/br]        if (result == NULL) {[br][/br][br][/br]            result = node;[br][/br][br][/br]            iter = result;[br][/br][br][/br]        }[br][/br][br][/br]        else {[br][/br][br][/br]            iter->next = node;[br][/br][br][/br]            iter = node;[br][/br][br][/br]        }[br][/br][br][/br]    }[br][/br][br][/br]    if (carry == 1) {[br][/br][br][/br]        node = (struct ListNode *)malloc(sizeof(struct ListNode));[br][/br][br][/br]        node->val = 1;[br][/br][br][/br]        iter->next = node;[br][/br][br][/br]    }[br][/br][br][/br]    return result;[br][/br][br][/br]}[br][/br][br][/br]
大家帮我看看啥问题。


谢谢!
5条回复
热度排序

发表回复