[英]Add 2 Numbers using linked lists - fail with large numbers - C
在 leetcode 上,我發現了使用單鏈表添加兩個數字的問題。 我還是個初學者。 我已經編寫了一個代碼,它適用於前幾個測試用例,但它會因較大的測試用例而失敗,例如
[1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
[5,6,4]
我的 output:
[-3,-4,-3,-5,-7,-7,-4,-5,-8,-6,-3,0,-2,-7,-3,-3,-2,-2,-9]
預期的:
[6,6,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]
我的代碼:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2)
{
//extracting value of first list
int cnt1 = -1;
long long int sum1 = 0;
struct ListNode *q = l1;
while (q != NULL) {
cnt1++;
sum1 = sum1 + q->val * pow(10, cnt1);
q = q->next;
}
printf("%d, %d\n", cnt1, sum1);
//extracting value of second list
int cnt2 = -1;
long long int sum2 = 0;
struct ListNode *p = l2;
while (p != NULL) {
cnt2++;
sum2 = sum2 + p->val * pow(10, cnt2);
p = p->next;
}
printf("%d, %d\n", cnt2, sum2);
long long int finalSum = sum1 + sum2;
printf("%d\n", finalSum);
struct ListNode *retRoot = malloc(sizeof(struct ListNode));
struct ListNode *t = malloc(sizeof(struct ListNode));
//putting the final sum into the list
long long int newSum;
retRoot->val = finalSum % 10;
retRoot->next = malloc(sizeof(struct ListNode));
newSum = finalSum / 10;
if (newSum == 0) {
retRoot->next = NULL;
return retRoot;
}
t = retRoot->next;
while (newSum != 0) {
//printf("newSum: %d\n", newSum);
t->val = newSum % 10;
newSum = newSum / 10;
if (newSum == 0) break;
t->next = malloc(sizeof(struct ListNode));
t = t->next;
}
t->next = NULL;
return retRoot;
}
您的 function 最初是錯誤的,至少因為列表可能包含太大的數字,無法存儲在任何基本的 integer 類型中。 所以例如在這個聲明中
sum1 = sum1 + q->val * pow(10, cnt1);
可能有溢出。
或此聲明中的 memory 分配
struct ListNode *t = malloc(sizeof(struct ListNode));
產生 memory 泄漏。
而且這個代碼片段
t = retRoot->next;
while (newSum != 0) {
//printf("newSum: %d\n", newSum);
t->val = newSum % 10;
//...
導致未定義的行為。
function可以看如下方式
struct ListNode * addTwoNumbers( const struct ListNode *l1, const struct ListNode *l2 )
{
const int Base = 10;
struct ListNode *head = NULL;
struct ListNode **current = &head;
int overflow = 0;
for ( ; l1 != NULL || l2 != NULL; current = &( *current )->next )
{
*current = malloc( sizeof( struct ListNode ) );
int sum = overflow;
if ( l1 != NULL )
{
sum += l1->val;
l1 = l1->next;
}
if ( l2 != NULL )
{
sum += l2->val;
l2 = l2->next;
}
( *current )->val = sum % Base;
overflow = sum / Base;
( *current )->next = NULL;
}
if ( overflow )
{
*current = malloc( sizeof( struct ListNode ) );
( *current )->val = overflow;
( *current )->next = NULL;
}
return head;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.