1. 程式人生 > >Leetcode 2.Add Two Numbers的c語言解決

Leetcode 2.Add Two Numbers的c語言解決

// Definition for singly-linked list.
/*    struct ListNode {
      int val;
      struct ListNode *next;
  };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
    //分配結果空間
    struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode)),*p=l1,*q=l2;
    result->val = 0; result->next = NULL;
    struct ListNode* head = result;
    //設定進位標誌
    int add = 0;
    while(p!=NULL && q!=NULL)
    {
        if(p->val+q->val >= 10)
            {add = 1;}
        //
        result->val += (p->val + q->val)%10;
        p = p->next; q = q->next;
        result->next =(struct ListNode*)malloc(sizeof(struct ListNode));
        //根據進位值選擇下一位的初始值
        if(add)
        {result->next->val = 1;add = 0;}
        else
        {result->next->val = 0;}
        result->next->next = NULL;
        result = result->next;
    }
    //多出來直接賦值
    while(p)
    {
        result->next =(struct ListNode*)malloc(sizeof(struct ListNode));
        result->next->val = 0; result->next->next = NULL;
        result = result->next;
        result->val = p->val; p = p->next;
    }
    while(q)
    {
        result->next =(struct ListNode*)malloc(sizeof(struct ListNode));
        result->next->val = 0; result->next->next = NULL;
        result = result->next;
        result->val = q->val; q = q->next;
    }
    //如果最後一位為0那麼直接釋放該空間
    if(!result->val) free(result);
    return head;

}


但是有個問題,就是為什麼加了free(result)會產生runtime error問題