https://leetcode.com/problems/add-two-numbers/
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes 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.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
很简单直观的一道题,有趣的地方在于首结点的处理,我收到了思维定式的影响,将结果组织成了使用头指针(而不是头节点)的链表 ,因此引入了头几行的特殊处理,好在题目中是确保了非空链表输入,如果输入中有特殊情况则需要更多的特殊处理,引入了复杂性。但其实我只需要返回一个指向链表首节点的指针就可以了,我为什么不能引入头节点呢?看到别人写的代码我才恍然大悟这一点。此外别人的代码里对于“ ? : ”表达式用的也是挺酷的,或许可以适当的学习一下,让代码看上去更流畅自然一点。
我的答案:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
static int fast_io = []() { std::ios::sync_with_stdio(false); cin.tie(nullptr); return 0; }();
ListNode *result = new ListNode((l1->val+l2->val)%10);
ListNode *cur = result;
int inc = (l1->val+l2->val)/10;
l1 = l1->next;
l2 = l2->next;
while(l1 != NULL && l2 != NULL){
cur->next = new ListNode((l1->val+l2->val+inc)%10);
inc = (l1->val+l2->val+inc)/10;
l1 = l1->next;
l2 = l2->next;
cur = cur->next;
}
while(l1 != NULL){
cur->next = new ListNode((l1->val+inc)%10);
inc = (l1->val+inc)/10;
l1 = l1->next;
cur = cur->next;
}
while(l2 != NULL){
cur->next = new ListNode((l2->val+inc)%10);
inc = (l2->val+inc)/10;
l2 = l2->next;
cur = cur->next;
}
if(inc != 0){
//cout << "det";
cur->next = new ListNode(1);
}
return result;
}
};
别人的答案:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
int x=[](){
std::ios::sync_with_stdio(false);
cin.tie(NULL);
return 0;
}();
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry = 0;
ListNode* presult = new ListNode(0);
ListNode *tresult = presult;
for (ListNode *pl1 = l1, *pl2 = l2; ((pl2 != nullptr) || (pl1 != nullptr));
pl1 = (pl1 == nullptr ? nullptr : pl1->next), pl2 = (
pl2 == nullptr ? nullptr : pl2->next), presult = presult->next)
{
int vl1 = (pl1 == nullptr ? 0 : pl1->val);
int vl2 = (pl2 == nullptr ? 0 : pl2->val);
int vsum = (vl1 + vl2 + carry) % 10;
carry = (vl1 + vl2 + carry) / 10;
presult->next = new ListNode(vsum);
}
if (carry > 0)
presult->next = new ListNode(carry);
ListNode *rtresult = tresult -> next;
delete tresult;
return rtresult;
}
};