当前位置:网站首页>两个链表相加
两个链表相加
2022-08-09 12:01:00 【爱敲代码的Harrison】
题目
力扣链接:两数相加
方法一:把链表转换为数字再相加?但是链表的长度可能会很长,就算是long类型长度也不够,所以此方法不可取!
方法二:利用容器?遍历链表,然后生成一个相应长度的数组,再将链表中的每个值拷贝进数组;另外一个链表也是如此。然后将数组中的每一个数对应相加,但是要处理好进位!最后通过数组形式还原成链表。此方法可以在笔试时候用,因为笔试不会太看重空间复杂度,并且此方法coding相比第三种方法稍微没那么容易出错,很可能笔试时候想不到第三种方法。
方法三:看代码
代码
package com.harrison.class06;
/** * @author Harrison * @create 2022-06-19-16:22 * @motto 众里寻他千百度,蓦然回首,那人却在灯火阑珊处。 */
public class Code08_AddTwoNumbers {
public class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public ListNode addTwoNumbers(ListNode head1, ListNode head2) {
int len1 = listLen(head1);
int len2 = listLen(head2);
ListNode l = len1 >= len2 ? head1 : head2;
ListNode s = l == head1 ? head2 : head1;
ListNode curL = l;
ListNode curS = s;
ListNode last = curL;
int carry = 0;
int curNum = 0;
while (curS != null) {
curNum = curS.val + curL.val + carry;
curL.val = (curNum % 10);
carry=(curNum/10);
last=curL;
curL=curL.next;
curS= curS.next;
}
while(curL!=null){
curNum=curL.val+carry;
curL.val=(curNum%10);
carry=(curNum/10);
last=curL;
curL= curL.next;
}
if(carry!=0){
last.next=new ListNode(1);
}
return l;
}
public static int listLen(ListNode head) {
int len = 0;
while (head != null) {
len++;
head = head.next;
}
return len;
}
}
边栏推荐
- Here comes the question: Can I successfully apply for 8G memory on a machine with 4GB physical memory?
- The redis library cannot be imported
- 中科院打脸谷歌:普通电脑追上量子优越性,几小时搞定原本要一万年的计算...
- C# 获取系统已安装的.NET版本
- AQS同步组件-FutureTask解析和用例
- 你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
- Blocking, non-blocking, multiplexing, synchronous, asynchronous, BIO, NIO, AIO all in one pot
- MySQL principle and optimization of Group By optimization techniques
- ABAP 报表中如何以二进制方式上传本地文件试读版
- Experiment record: the process of building a network
猜你喜欢
2022 Niu Ke Duo School (6) M. Z-Game on grid
阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端
h264协议
#Internet of Things essay#Xiaoxiong pie equipment development actual combat
shell脚本------函数的格式,传参,变量,递归,数组
【Untitled】
曼城推出可检测情绪的智能围巾,把球迷给整迷惑了
ThreadLocal的简单理解
二重指针-char **、int **的作用
900页数学论文证明旋转的黑洞不会爆炸,丘成桐:30多年来广义相对论首次重大突破...
随机推荐
修改VOT2018.json文件,去掉图片路径中的color
香港服务器如何进行加密?
HAproxy: load balancing
electron 应用开发优秀实践
FFmpeg库在win10上配置使用(不配置libx264)
The core key points of microservice architecture
实验记录:搭建网络过程
京东架构师呕心整理:jvm与性能调优有哪些核心技术知识点
How to upload local file trial version in binary mode in ABAP report
从零开始Blazor Server(9)--修改Layout
你没见过的《老友记》镜头,AI给补出来了|ECCV 2022
阻塞、非阻塞、多路复用、同步、异步、BIO、NIO、AIO 一锅端
Manchester city launch emotional intelligence scarf can be detected, give the fans
非科班AI小哥火了:他没有ML学位,却拿到DeepMind的offer
redis库没法引入
【微服务~远程调用】整合RestTemplate、WebClient、Feign
WPF 实现带蒙版的 MessageBox 消息提示框
web课程设计
Adalvo acquires its first branded product, Onsolis
Nature:猪死亡1小时后,器官再次运转