好久没有写C了,LeetCode上面的一道题:
You are given two non-empty linked lists representing two non-negative
The digits are stored in reverse order and each of their
contain a single digit. Add the two numbers and return it as a
linked list.
You may assume the two numbers do not contain any leading zero, except
the number 0 itself.Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8
我的代码:
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) { struct ListNode* result = (struct ListNode*)malloc(sizeof(struct ListNode)); result->next = NULL; struct ListNode* result_temp = result; struct ListNode* l1_node; struct ListNode* l2_node; l1_node = l1; l2_node = l2; while (l1_node != NULL || l2_node != NULL) { struct ListNode* result_node = (struct ListNode*)malloc(sizeof(struct ListNode)); result_node->val = 0; result_node->next = NULL; if (l1_node != NULL) { result_node->val += l1_node->val; l1_node = l1_node->next; } if (l2_node != NULL) { result_node->val += l2_node->val; l2_node = l2_node->next; } while (result_temp->next!= NULL) { result_temp = result_temp->next; } result_temp->next = result_node; } result_temp = result->next; while (result_temp != NULL) { if (result_temp->val >= 10) { if (result_temp->next != NULL) { result_temp->next->val++; } else { struct ListNode* last_node = (struct ListNode*)malloc(sizeof(struct ListNode)); last_node->val = 1; last_node->next = NULL; result_temp->next = last_node; } result_temp->val = result_temp->val - 10; } result_temp = result_temp->next; } return result->next; }
对比下大神写的代码(C++):
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { ListNode preHead(0), *p = &preHead; int extra = 0; while (l1 || l2 || extra) { int sum = (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra; extra = sum / 10; p->next = new ListNode(sum % 10); p = p->next; l1 = l1 ? l1->next : l1; l2 = l2 ? l2->next : l2; } return preHead.next;}