双指针
2. 两数相加:基础题,模拟加法计算过程,注意补位与进位即可,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(); ListNode* p = new ListNode(); ListNode* q = new ListNode(); dummy->next = p; ListNode* p1 = l1, *p2 = l2; while(p1->next != nullptr || p2->next != nullptr) { if (p1->next == nullptr && p2->next != nullptr) p1->next = new ListNode(0); if (p2->next == nullptr && p1->next != nullptr) p2->next = new ListNode(0); p1 = p1->next; p2 = p2->next; } p1 = l1, p2 = l2; bool carray = false; while (p1 != nullptr) { int num = 0; if (carray) { num = p1->val + p2->val + 1; } else { num = p1->val + p2->val; } p->val = num%10; if (num >= 10) carray = true; else carray = false; p1 = p1->next; p2 = p2->next; p->next = new ListNode(); q = p; p = p->next; } if (carray) p->val = 1; else { q->next = nullptr; } return dummy->next; } };
|