纯水题,想来想去指针链表类题目怎么都还是C++比较好。环境里默认没有NULL,就先用0代替了。觉得风格比较烂。
后找到一个更精炼的代码,一是使用二级指针,省了一个前向变量,二是二链表同时前进结束后,做个简单判断,就不用两个while了。三是进位不知道,随便起了个up,其实overflow或是carry都要好多了。
本人的代码:
class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { // Start typing your C/C++ solution below // DO NOT write int main() function int up = 0; ListNode * head = 0; ListNode * last = 0; ListNode * tmp = 0; while (l1 != 0 && l2 != 0) { int val = 0; calculateValueAndUp(&val, &up, l1->val, l2->val); tmp = new ListNode(val); if (head == 0) { head = tmp; } else { last->next = tmp; } last = tmp; l1 = l1->next; l2 = l2->next; } while (l1 != 0) { int val = 0; calculateValueAndUp(&val, &up, l1->val, 0); tmp = new ListNode(val); if (head == 0) { head = tmp; } else { last->next = tmp; } last = tmp; l1 = l1->next; } while (l2 != 0) { int val = 0; calculateValueAndUp(&val, &up, 0, l2->val); tmp = new ListNode(val); if (head == 0) { head = tmp; } else { last->next = tmp; } last = tmp; l2 = l2->next; } if (up == 1) { tmp = new ListNode(1); last->next = tmp; } return head; } void calculateValueAndUp(int* val, int* up, int a, int b) { *val = a + b + *up; if (*val >= 10) { *val -= 10; *up = 1; } else { *up = 0; } } };
更好的代码
class Solution { public: ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) { int overflow = 0; ListNode *ret = NULL; ListNode **pnode = &ret; while(l1 && l2) { int val = l1->val + l2->val + overflow; overflow = val / 10; *pnode = new ListNode(val % 10); pnode = &((*pnode)->next); l1 = l1->next; l2 = l2->next; } ListNode *lremain = l1 ? l1 : l2; while(lremain) { int val = lremain->val + overflow; overflow = val / 10; *pnode = new ListNode(val % 10); pnode = &((*pnode)->next); lremain = lremain->next; } if(overflow > 0) { *pnode = new ListNode(overflow); } return ret; } };