You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
将长度较短的链表在末尾补零使得两个连表长度相等,再一个一个元素对其相加(考虑进位)
1.获取两个链表所对应的长度
2.在较短的链表末尾补零
3.对齐相加考虑进位
Solution: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
36public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode r = new ListNode(0);
ListNode h = r;
ListNode beforeend = r;
while(l1 != null && l2!= null){
r.val += l1.val + l2.val;
r.next = new ListNode(r.val / 10);
r.val %= 10;
beforeend = r;
r = r.next;
l1 = l1.next;
l2 = l2.next;
}
ListNode rest;
if (l1 == null) rest = l2; else rest =l1;
while(rest != null){
r.val += rest.val;
r.next = new ListNode(r.val / 10);
r.val %= 10;
beforeend = r;
r = r.next;
rest = rest.nest;
}
if(beforeend.next != null && beforeend.next.val == 0) beforeend.next=null;
return h;
}
}