两个链表,里面是数字,然后做相加,返回
https://leetcode-cn.com/problems/add-two-numbers/
//两个链表里面数字加上
//
public class Code01_AddTwoNumber {
public static class ListNode {
public int val;
public ListNode next;
public ListNode(int val) {
this.val = val;
}
public ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}
public static ListNode addTwoNumber(ListNode head1,ListNode head2){
int length1 = getLength(head1);
int length2 = getLength(head2);
ListNode l = length1 > length2 ? head1:head2;
ListNode s = l == head1 ?head2:head1;
ListNode curL = l;
ListNode curS = s;
//这里的last设置等于长链表,并且在后续计算的时候,一直等于curL,是为了最后在只加进位信息的时候,知道节点挂在那里
ListNode last = curL;
//这里设置的数用来进位使用
int carry = 0 ;
int curNum = 0;
//先循环短链表
while (curS != null){
//计算这个位置,长链表和短链表,以及进位相加的数
curNum = curL.val + curS.val+carry;
//长链表是需要返回的,所以 模10剩下的就是要长链表的值
curL.val = curNum % 10 ;
//相加的值除以10,算出来是否要进位
carry = curNum / 10 ;
last =curL;
//这里将长短链表都指向自己链表的下一个位置,继续计算
curL = curL.next;
curS = curS.next;
}
//如果段链表循环完成,判断长链表是否为null
while (curL != null){
curNum = curL.val + carry;
curL.val = curNum % 10 ;
carry = curNum / 10 ;
last = curL;
curL = curL.next;
}
//如果都为空,判断进位是否有值,有值需要新增一个节点来放
if(carry != 0){
last.next = new ListNode(1);
}
return l;
}
public static int getLength(ListNode head){
int length = 0;
while (head.next != null){
length ++;
head = head.next;
}
return length;
}
}