题目:
- 2.两数相加
- 给你两个非空的链表,表示两个非负的整数。它们每位数字都是按逆序的方式存储的,并且每个节点只能存储一位数字。
- 请你将两个数相加,并以相同形式返回一个表示和的链表。
- 你可以假设除了数字 0 之外,这两个数都不会以 0开头。
代码
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; }
}
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tmp =null;
int carry = 0;
while (l1!= null||l2!=null) {
int n1 = l1!=null?l1.val:0;
int n2 = l2 !=null?l2.val:0;
int sum = n1 + n2 + carry;
if(head==null){
head = tmp = new ListNode(sum%10);
}else {
tmp.next = new ListNode(sum%10);
tmp = tmp.next;
}
carry = sum/10;
if(l1!=null){
l1 = l1.next;
}
if(l2!=null){
l2 = l2.next;
}
}
if(carry>0){
tmp.next = new ListNode(carry);
}
return head;
}
public List play(ListNode node){
List<Integer> list = new ArrayList<>();
while (node!=null){
list.add(node.val);
node = node.next;
}
return list;
}
public static void main(String[] args) {
Solution solution = new Solution();
ListNode l1 =null,head1 = null;
ListNode l2 =null,head2 = null;
Random rand = new Random();
int i_max = rand.nextInt(20)+1;
int j_max = rand.nextInt(20)+1;
for(int i = 0; i<i_max; i++) {
if (l1 == null) {
head1 = l1 = new ListNode(rand.nextInt(8) + 1);
} else {
head1.next = new ListNode(rand.nextInt(8) + 1);
head1 = head1.next;
}
}
for(int j = 0; j<j_max; j++) {
if(l2==null){
head2 = l2 = new ListNode(rand.nextInt(8)+1);
}else {
head2.next = new ListNode(rand.nextInt(8)+1);
head2 = head2.next;
}
}
System.out.println(solution.play(l1));
System.out.println(solution.play(l2));
System.out.println(solution.play(solution.addTwoNumbers(l1,l2)));
}
}
测试结果
[1, 6, 3, 5, 3, 3, 1, 5, 6, 1, 3, 8, 7, 8, 7, 8]
[2, 4, 6, 4, 6, 3, 4, 4, 4, 4, 4, 8, 6, 1, 8]
[3, 0, 0, 0, 0, 7, 5, 9, 0, 6, 7, 6, 4, 0, 6, 9]