题目
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807.
示例 2:输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
我的思路
把链表的数一个一个取出来相加,不过没考虑进位,最后也没有提交成功
/**
* 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) {
int numa=0;
int numb=0;
int res=0;
int a=1,b=1,c=0,aa=0,bb=0,cc=0;
ListNode ans=new ListNode(0);
ListNode current = ans;
while(l1.next!=null)
{
numa=numa+a*l1.val;
a=a*10;
aa++;
l1=l1.next;
}
while(l2.next!=null)
{
numb=numb+b*l2.val;
b=b*10;
bb++;
l2=l2.next;
}
res=numa+numb;
if(a>b)
{
c=a;
}
else{
c=b;
}
for(int i=1;i<=cc;i++)
{
ListNode node = new ListNode(i);
current.next=node;
current=current.next;
}
current=ans;
while(c!=1)
{
current.val=res%c;
c=c/10;
res=res/10;
current=current.next;
}
current.next=null;
return ans.next;
}
}
题解
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode head = null, tail = 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 = tail = new ListNode(sum % 10);
} else {
tail.next = new ListNode(sum % 10);
tail = tail.next;
}
carry = sum / 10;
if (l1 != null) {
l1 = l1.next;
}
if (l2 != null) {
l2 = l2.next;
}
}
if (carry > 0) {
tail.next = new ListNode(carry);
}
return head;
}
}