这道题让我想起了acwing里的高精度加法,因为这里的加法也是超过100位了。于是套着模板写了一下,然后看了一下评论区,发现链表再套vector属于是脱裤子放屁了
/** * 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) {} * }; */ #include <vector> class Solution { public: vector<int> add(vector<int> &a, vector<int> &b){ int t = 0; vector<int> c; for(int i = 0; i < a.size() || i < b.size(); i ++ ){ if(i < a.size()) t += a[i]; if(i < b.size()) t += b[i]; c.push_back(t % 10); t /= 10; } if(t) c.push_back(1); return c; } ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { vector<int> A, B; while(l1 != nullptr){ A.push_back(l1->val); l1 = l1->next; } while(l2 != nullptr){ B.push_back(l2->val); l2 = l2->next; } vector<int> c; c = add(A, B); ListNode *l3 = new ListNode(c[0]); ListNode *res = l3; int len = c.size(); for(int i = 1; i < len; i ++ ){ ListNode *next1 = new ListNode(c[i]); l3->next = next1; l3 = next1; } return res; } };
直接在链表的基础上做,注意和vector不太一样的是,每次加法的循环都要特别注意边界条件,注意两链表指针的更新。
/** * 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) { int t = 0;//存储每一位相加的信息 ListNode *l3 = new ListNode(-1); ListNode *res = l3; while(l1 != nullptr || l2 != nullptr){ if(l1 != nullptr){ t += l1->val; l1 = l1->next; } if(l2 != nullptr) { t += l2->val; l2 = l2->next; } l3->next = new ListNode(t % 10); t /= 10; l3 = l3->next; } if(t) l3->next = new ListNode(1);//如果最后最高位有进位,还得补一个1 return res->next; } };
标签:ListNode,val,int,相加,next,l2,l1,Leetcode From: https://www.cnblogs.com/luxiayuai/p/17311854.html