题目描述
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
思路很明确,主要是要判断的是是否有进位,并且根据是否有进位来判断是否需要来建立新的节点存储一个进位数
我的代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
/*输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
将l1作为返回值,即将所有的加法放入到
*/
int jinwei = 0;
int size1 = 0;
int size2 = 0;
ListNode tem1 = l1;
ListNode tem2 = l2;
//分别计算两个的长度,我们最后以最长的链表最为返回的结果
while (tem1!=null) {
tem1 = tem1.next;
size1++;
}
while (tem2!=null) {
tem2 = tem2.next;
size2++;
}
//tem 是最长的那个链表的头
ListNode tem = size1 >= size2? l1 : l2;
if(size1 >= size2){
//l1长度大于l2,那么就要以l1作为计算的值
while (l2!=null) {
int t = l1.val + l2.val + jinwei;
l1.val = t % 10;
jinwei = t / 10;
//如果两个长度一致,并且有进位
if(l1.next == null && l2.next == null && jinwei ==1){
ListNode teListNode = new ListNode(1);
teListNode.next = null;
l1.next = teListNode;
return tem;
}
l1 = l1.next;
l2 = l2.next;
}
while (l1!=null) {
int t = l1.val + jinwei;
l1.val = t % 10;
jinwei = t / 10;
//如果最后一位有进位
if(l1.next == null && jinwei ==1){
ListNode teListNode = new ListNode(1);
teListNode.next = null;
l1.next = teListNode;
return tem;
}
l1 = l1.next;
}
}else {
//l2长度大于l1,那么就要以l2作为计算的值
while (l1 != null) {
int t = l1.val + l2.val + jinwei;
l2.val = t % 10;
jinwei = t / 10;
l1 = l1.next;
l2 = l2.next;
}
while (l2!=null) {
int t = l2.val + jinwei;
l2.val = t % 10;
jinwei = t / 10;
if(l2.next == null && jinwei ==1){
ListNode teListNode = new ListNode(1);
teListNode.next = null;
l2.next = teListNode;
return tem;
}
l2 = l2.next;
}
}
return tem;
}
}
有点冗余其实,可以写一个函数来进行这一系列的变换
排名靠前的代码
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
return addTwoNumbers(l1,l2,0);
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2, int increase) {
if (l1 != null && l2 != null) {
ListNode l1Next = l1.next;
ListNode l2Next = l2.next;
int sum = l1.val + l2.val + increase;
if (sum >= 10) {
ListNode newNode = new ListNode(sum-10);
newNode.next = addTwoNumbers(l1Next,l2Next,1);
return newNode;
}else {
ListNode newNode = new ListNode(sum);
newNode.next = addTwoNumbers(l1Next,l2Next,0);
return newNode;
}
}else if(l1 != null){
return withNum(l1,increase);
}else if(l2 != null) {
return withNum(l2,increase);
}else{
if(increase > 0) {
return new ListNode(1);
}else{
return null;
}
}
}
public ListNode withNum(ListNode l1,int increase) {
int sum = l1.val + increase;
if (sum >= 10) {
ListNode newNode = new ListNode(sum-10);
if (l1.next != null) {
newNode.next = withNum(l1.next,1);
}else{
newNode.next = new ListNode(1);
}
return newNode;
}else {
ListNode newNode = new ListNode(sum);
newNode.next = l1.next;
return newNode;
}
}
}