问题1
int* twoSum(int* nums, int numsSize, int target, int* returnSize){int i = 0, j = 0;int numlist[2];for (i = 0; i < numsSize; i++){for (j = 0; j < numsSize; j++) {if (target == nums[i] + nums[j]) {numlist[0] = nums[i];numlist[1] = nums[j];*returnSize = 2;return numlist;}}}*returnSize = 0;return numlist;
}
这段程序在编译时会发生报错
问题原因
这个函数的问题在于它返回了一个指向局部变量的指针。在函数结束时,局部变量numlist的内存空间将被释放,因此返回的指针将指向无效的内存位置。这可能会导致未定义的行为或程序崩溃。
要解决这个问题,可以使用动态分配内存来创建一个新的数组,或者将数组作为参数传递给函数并在函数内部修改它。
解决方式
int* twoSum(int* nums, int numsSize, int target, int* returnSize){int i = 0, j = 0;int *numlist = malloc(sizeof(int) * 2);for (i = 0; i < numsSize; i++){for (j = 0; j < numsSize; j++) {if (target == nums[i] + nums[j]) {numlist[0] = i;numlist[1] = j;*returnSize = 2;return numlist;}}}*returnSize = 0;return numlist;
}
问题2
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){struct ListNode* sum = (struct ListNode*)malloc(sizeof(struct ListNode));struct ListNode* tmp1;struct ListNode* tmp2;tmp1 = l1;tmp2 = l2;while (tmp1 || tmp2){int tmpv1 = tmp1 ? tmp1->val : 0;int tmpv2 = tmp2 ? tmp2->val : 0;sum->val = tmpv1 + tmpv2;tmp2 = tmp2 ? tmp2->next : NULL;tmp1 = tmp1 ? tmp1->next : NULL;if (tmp1 || tmp2) {sum->next = (struct ListNode*)malloc(sizeof(struct ListNode));sum = sum->next;} else {sum->next = NULL;}}return sum;
}
返回的结果不对
问题原因
链表没有回归头结点
解决方式
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){struct ListNode* sum = (struct ListNode*)malloc(sizeof(struct ListNode));struct ListNode* tmp1;struct ListNode* tmp2;struct ListNode* tmpsum;int flag = 0;tmp1 = l1;tmp2 = l2;tmpsum = sum;while (tmp1 || tmp2 || flag){int tmpv1 = tmp1 ? tmp1->val : 0;int tmpv2 = tmp2 ? tmp2->val : 0;tmpsum->val = tmpv1 + tmpv2 + flag;if (tmpsum->val >= 10) {flag = 1;tmpsum->val = tmpsum->val - 10;} else {flag = 0;}tmp2 = tmp2 ? tmp2->next : NULL;tmp1 = tmp1 ? tmp1->next : NULL;if (tmp1 || tmp2 || flag) {tmpsum->next = (struct ListNode*)malloc(sizeof(struct ListNode));tmpsum = tmpsum->next;} else {tmpsum->next = NULL;}}return sum;
}