题目描述

题目描述.png

解题思路

1
2
3
4
5
6
7
2-->4-->3
+
5-->6-->4
=
7-->10-->7
merge函数对每一位判断是否需要进行进位处理
7-->0-->8

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
/**
* Definition for singly-linked list.
* 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; }
* }
*/

class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head1=l1;
ListNode head2=l2;
while(head1!=null){//链表的遍历,同时对两个头结点进行判断
if(head2!=null)
{
head1.val+=head2.val;
head2=head2.next;
}
if(head1.next==null&&head2!=null){//当l2长度大于l1长度的处理方法
head1.next=head2;
break;
}
head1=head1.next;
}
merge(l1);
return l1;
}
//进位处理
public void merge(ListNode head){
while(head!=null){
if(head.val>=10){
head.val=head.val%10;
if(head.next==null){//需要进位时的处理方法
head.next=new ListNode(0);
}
head.next.val+=1;
}
head=head.next;
}
}
}

题目有三个注意点

  • l1>=l2长度时
  • l2>l1长度时
  • 在末位需要产生进位时

运行截图.png

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/add-two-numbers