当前位置:网站首页>链表中的数字相加----链表专题
链表中的数字相加----链表专题
2022-08-05 08:45:00 【ailigei】
链表中的数字相加


分析:
这是一个看起来还蛮简单的题目,很多初步学习算法的同学的第一反应是根据链表求出整数,然后直接将两个整数相加,最后把结果用链表表示。但是这种思路最大的问题是没有考虑到整数有可能会溢出,当链表较长时,表示的整数很大,可能会超过int甚至是long的范围,如果根据链表求出整数就有可能会溢出
通常,两个整数相加都是先加个数,再加十位数,然后依次相加更高位数字。由于题目中的整数使用单向链表表示,因此先将两个尾节点相加,再将两个整数的倒数第二个节点相加,并依次对前面的节点相加。
但是两个尾节点相加之后,在单向链表中就无法前进到倒数第二个节点。在单向链表中只能从前面的节点朝着next指针方向前进到后面的节点,却无法从后面的节点前进到前面的节点。
解决这个问题的办法就是把表示整数的链表反转,反转之后的链表的头节点表示个位数,尾节点表示最高位数,此时从两个链表的头结点开始相加,就相当于从整数的个位数开始相加。
做加法还需要要特别注意的是进位。如果两个整数的个位数相加和超过或者等于10,就会往十位数产生一个进位。在下一步做十位数相加时就要把这个进位考虑进去。
总体思路如下:
做加法:
最后将得到的结果再次反转:
最后贴代码:
import java.util.*;
/* * public class ListNode { * int val; * ListNode next = null; * } */
public class Solution {
/** * * @param head1 ListNode类 * @param head2 ListNode类 * @return ListNode类 */
//链表反转函数
public ListNode reverselist(ListNode head)
{
ListNode pre=null;
ListNode cur=head;
while(cur!=null)
{
ListNode next=cur.next;
cur.next=pre;
pre=cur;
cur=next;
}
return pre;
}
public ListNode addInList (ListNode head1, ListNode head2) {
ListNode dummy = new ListNode(0);//哨兵结点
ListNode summy=dummy;
//反转链表
head1=reverselist(head1);
head2=reverselist(head2);
//进位计数器
int carry=0;
while(head1!=null||head2!=null)
{
int sum=(head1==null?0:head1.val)+(head2==null?0:head2.val)+carry;
carry=sum>=10?1:0;
sum=sum>=10?sum-10:sum;
ListNode newnode=new ListNode(sum);
summy.next=newnode;
summy=newnode;
head1=head1==null?null:head1.next;
head2=head2==null?null:head2.next;
}
if(carry>0)
{
summy.next=new ListNode(carry);
}
return reverselist(dummy.next);
}
}
边栏推荐
猜你喜欢

基因数据平台

Embedded practice ---- based on RT1170 transplant memtester to do SDRAM test (25)

ps怎么拼图,自学ps软件photoshop2022,PS制作拼图效果

施一公:科学需要想象,想象来自阅读

sql server收缩日志的作业和记录,失败就是因为和备份冲突了吗?

Detailed explanation of DNS query principle

Why is pnpm hitting npm and yarn dimensionality reduction?

七夕看什么电影好?爬取电影评分并存入csv文件

网页直接访问链接不让安全中心拦截

代码审计—PHP
随机推荐
手机上流行的各类谜语
Comprehensively explain what is the essential difference between GET and POST requests?Turns out I always misunderstood
TensorFlow installation steps
IT研发/开发流程规范效能的思考总结
Luogu P4588: [TJOI2018]数学计算
路由----router
让程序员崩溃的N个瞬间(非程序员误入)
DNS 查询原理详解
工程制图知识点
施一公:科学需要想象,想象来自阅读
[Structural Internal Power Cultivation] Structural Realization Stages (2)
撕裂寂寞
Rotation of the displayed value on the button
ps怎么拼图,自学ps软件photoshop2022,PS制作拼图效果
mySQL数据库初始化失败,有谁可以指导一下吗
微信小程序请求封装
[Untitled] Long-term recruitment of hardware engineers-Shenzhen Baoan
嵌入式实操----基于RT1170 移植memtester做SDRAM测试(二十五)
tear apart loneliness
SQL SERVER on master-slave table trigger design