2. 两数相加
水题
设d为进位,每次两个对应位相加并加上d = tmp
新数字当前位 = tmp % 10
d = tmp / 10
注意nullptr
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode *ret = new ListNode(); ListNode *p = l1, *q = l2, *r = ret; int cnt = 0, d = 0; r->next = nullptr; while(p != nullptr || q != nullptr) { int tmp; if(p != nullptr && q != nullptr) tmp = p->val + q->val + d; else if(p != nullptr) tmp = p->val + d; else tmp = q->val + d; if(cnt++ == 0) { r->val = tmp % 10; } else { ListNode *node = new ListNode(); node->val = tmp % 10; node->next = nullptr; r->next = node; r = node; } d = tmp / 10; if(p) p = p->next; if(q) q = q->next; } if(d != 0) { ListNode *node = new ListNode(); node->val = d; r->next = node; r = node; } r->next = nullptr; return ret; } };
自己选择的路,跪着也要走完。朋友们,虽然这个世界日益浮躁起来,只要能够为了当时纯粹的梦想和感动坚持努力下去,不管其它人怎么样,我们也能够保持自己的本色走下去。