algorithm-base/animation-simulation/链表篇/面试题 02.05. 链表求和.md

111 lines
4.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [ 02.05. ](https://leetcode-cn.com/problems/sum-lists-lcci/)
k
西
>
1
```java
(7 -> 1 -> 6) + (5 -> 9 -> 2)617 + 295
2 -> 1 -> 9912
```
2
```java
(9 -> 9) + (9 -> 9),99+99
8->9->1
```
3
```java
(5)+(5),5+5
0->1
```
****
java int -2147483648 +2147483648 -2^31 2^31
10101
1.
2.
3.1.
0199+9=18
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/链表求和.1yh4ymdee3k0.gif)
nlist1summod1
```java
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
//返回链表
ListNode nList = new ListNode(-1);
ListNode tempnode = nList;
//用来保存进位值初始化为0
int summod = 0;
while(l1 != null || l2 != null) {
//如果l1的链表为空则l1num为0若是不为空则为链表的节点值
//判断是否为空为空就设为0
int l1num = l1 == null ? 0 : l1.val;
int l2num = l2 == null ? 0 : l2.val;
//将链表的值和进位值相加,得到为返回链表的值
int sum = l1num+l2num+summod;
//更新进位值例18/10=19/10=0
summod = sum/10;
//新节点保存的值18 % 8=2则添加2
sum = sum%10;
//添加节点
tempnode.next = new ListNode(sum);
//移动指针
tempnode = tempnode.next;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
//最后根据进位值判断需不需要继续添加节点
if (summod == 1) {
tempnode.next = new ListNode(summod);
}
return nList.next;
}
}
```