网站优化的文章,备案的网站是公司吗,建设一个网站的好处,个人网站制作手机版题解目录 1、题目描述解释2、算法原理解析3、代码编写#xff08;原始版本#xff09;4、代码编写#xff08;优化版本#xff09; 1、题目描述解释 2、算法原理解析 3、代码编写#xff08;原始版本#xff09;
/*** Definition for singly-linked list.* struct ListN… 题解目录 1、题目描述解释2、算法原理解析3、代码编写原始版本4、代码编写优化版本 1、题目描述解释 2、算法原理解析 3、代码编写原始版本
/*** 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* new_headnew ListNode(0);ListNode* ptailnew ListNode(0);//使用两个指针分别指向两个链表的头结点ListNode* cur1l1;ListNode* cur2l2;int t0;//记录相加后的数字int num0;//记录个位while(cur1cur2){ttcur1-valcur2-val;//取出个位numt%10;//插入到新节点后面if(new_head-nextnullptr){ListNode* newNodenew ListNode(num);new_head-nextnewNode;ptailnewNode;}else{ListNode* newNodenew ListNode(num);ptail-nextnewNode;ptailnewNode;}t/10;cur1cur1-next;cur2cur2-next;}//判断是哪个先走完if(cur1nullptr){//把cur2的后面加入while(cur2){ttcur2-val;numt%10;ListNode* newNodenew ListNode(num);ptail-nextnewNode;ptailnewNode;t/10;cur2cur2-next;}}if(cur2nullptr){//把cur1的后面加入while(cur1){ttcur1-val;numt%10;ListNode* newNodenew ListNode(num);ptail-nextnewNode;ptailnewNode;t/10;cur1cur1-next;}}//判断t是否为0if(t){ListNode* newNodenew ListNode(t);ptail-nextnewNode;ptailnewNode;}return new_head-next;}
};4、代码编写优化版本
/*** 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* NewHeadnew ListNode(0);ListNode* PtailNewHead;ListNode* cur1l1;ListNode* cur2l2;int t0;while(cur1||cur2||t)//都为假才跳出循环{if(cur1){tcur1-val;cur1cur1-next;}if(cur2){tcur2-val;cur2cur2-next;}Ptail-nextnew ListNode(t%10);PtailPtail-next;t/10;}//释放资源PtailNewHead-next;delete NewHead;return Ptail;}
};