2021年3月31日星期三

What's wrong in my link-list code for C? `Add Two Numbers`

Problem 2 on Leetcode:

Add Two Numbers.

My code here:

#include <stdbool.h>  #include <stdio.h>  #include <stdlib.h>  struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){    struct ListNode* result;      volatile bool carry = false;    while ((l1 != NULL) || (l2 != NULL) ) {      result = (struct ListNode*)malloc(sizeof(struct ListNode) );      result->next = NULL;      int v1 = 0;           if (l1 != NULL) {        v1 = l1->val;        l1 = l1->next;      }            int v2 = 0;           if (l2 != NULL) {        v2 = l2->val;        l2 = l2->next;      }                int sum = v1 + v2;      if (carry == true)        sum += 1;      carry = (sum > 9);                result->val = sum%10;      printf("result->val: %d, sum: %d, carry: %d\n",result->val,sum,carry);       //result = result->next;      }        return result;  }  

Input

[2,4,3]  [5,6,4]  

Expect

[7,0,8]  

Stdout

result->val: 7, sum: 7, carry: 0  result->val: 0, sum: 10, carry: 1  result->val: 8, sum: 8, carry: 0  

Actully out:

[8]  

I think maybe loss

result = result->next;  

in while loop,

so I add it after printf().

But Output seems null

[]  

What's wrong in my code?

https://stackoverflow.com/questions/66898202/whats-wrong-in-my-link-list-code-for-c-add-two-numbers April 01, 2021 at 11:53AM

没有评论:

发表评论