leetcode 2. 兩數相加 C語言版
阿新 • • 發佈:2018-11-11
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode* l = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* p = l1,* q = l2, * t = l; t->val = 0; t->next = NULL; while(p != NULL&&q != NULL) { struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = 0; node->next = NULL; t->next = node; t->val += (p->val + q->val); if(t->val >= 10) { t->val -= 10; node->val = 1; } p = p->next; q = q->next; if(p == NULL&&q == NULL&&t->next->val == 0) //防止最後出現一個0 t->next = NULL; t = t->next; } while(p != NULL) //l1未結束而l2結束了 { struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = 0; node->next = NULL; t->next = node; t->val += p->val; if(t->val >= 10) { t->val -= 10; node->val = 1; } p = p->next; if(p == NULL&&t->next->val == 0) t->next = NULL; t = t->next; } while(q != NULL) //l2未結束而l1結束了 { struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode)); node->val = 0; node->next = NULL; t->next = node; t->val += q->val; if(t->val >= 10) { t->val -= 10; node->val = 1; } q = q->next; if(q == NULL&&t->next->val == 0) t->next = NULL; t = t->next; } return l; }