当前位置: 首页 > news >正文

【力扣专题栏】两数相加,如何实现存储在链表中的整数相加?

在这里插入图片描述

题解目录

  • 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_head=new ListNode(0);ListNode* ptail=new ListNode(0);//使用两个指针分别指向两个链表的头结点ListNode* cur1=l1;ListNode* cur2=l2;int t=0;//记录相加后的数字int num=0;//记录个位;while(cur1&&cur2){t=t+cur1->val+cur2->val;//取出个位num=t%10;//插入到新节点后面if(new_head->next==nullptr){ListNode* newNode=new ListNode(num);new_head->next=newNode;ptail=newNode;}else{ListNode* newNode=new ListNode(num);ptail->next=newNode;ptail=newNode;}t/=10;cur1=cur1->next;cur2=cur2->next;}//判断是哪个先走完if(cur1==nullptr){//把cur2的后面加入while(cur2){t=t+cur2->val;num=t%10;ListNode* newNode=new ListNode(num);ptail->next=newNode;ptail=newNode;t/=10;cur2=cur2->next;}}if(cur2==nullptr){//把cur1的后面加入while(cur1){t=t+cur1->val;num=t%10;ListNode* newNode=new ListNode(num);ptail->next=newNode;ptail=newNode;t/=10;cur1=cur1->next;}}//判断t是否为0if(t){ListNode* newNode=new ListNode(t);ptail->next=newNode;ptail=newNode;}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* NewHead=new ListNode(0);ListNode* Ptail=NewHead;ListNode* cur1=l1;ListNode* cur2=l2;int t=0;while(cur1||cur2||t)//都为假,才跳出循环{if(cur1){t+=cur1->val;cur1=cur1->next;}if(cur2){t+=cur2->val;cur2=cur2->next;}Ptail->next=new ListNode(t%10);Ptail=Ptail->next;t/=10;}//释放资源Ptail=NewHead->next;delete NewHead;return Ptail;}
};

http://www.mrgr.cn/news/59603.html

相关文章:

  • Linux相关概念和易错知识点(16)(Shell原理、进程属性和环境变量表的联系)
  • ElfBoard技术贴|ELF 1开发板适配的电容触摸液晶模块详解
  • Vue开发
  • 【商汤科技-注册/登录安全分析报告】
  • 间接寻址、基址寻址、相对寻址和变址寻址
  • cherry pick commit
  • jsMind:炸裂项目,用JavaScript构建的思维导图库,GitHub上的热门开源项目
  • 学习qmake
  • 移情别恋c++ ദ്ദി˶ー̀֊ー́ ) ——15.C++11(1)
  • jsoup常用语法功能汇总
  • 通过企业架构蓝图(EA Blueprint)构建企业数字化转型之路
  • 文件实时备份软件下载
  • 充分统计量
  • MediaGo(m3u8视频下载工具) v3.0.0.5 免费版
  • w~大模型~合集11
  • .net core 读取 appsettings.json 值
  • 基于SSM轻型卡车零部件销售系统的设计
  • 对角两对双差速轮AGV的动力学解算
  • SpringBoot中yaml配置文件中文字符异常以及将多个独立的IDEA项目整合到一个项目里当做模块的处理
  • visual studio断点无法命中
  • 【学术论文投稿】Windows11开发指南:打造卓越应用的必备攻略
  • Oracle 第7章:数据完整性约束
  • 10月27日
  • 【前端面试】Typescript
  • 【遗传算法】基于遗传模拟退火算法的风电功率聚类分析
  • springboot094基于web的酒店客房管理系统(论文+源码)_kaic