题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// 空处理
if(head1 == null){
return head2;
}else if(head2 == null){
return head1;
}
// 首先将链表反转
head1 = reverse(head1);
head2 = reverse(head2);
// 这里专门创建一个链表存储新数据
ListNode head = new ListNode(-1);
ListNode fllowHead = head;
// 进位数据
int carry = 0;
// 进行运算(这里当两者都不存在了再结束,在内部判断是否存在)
while(head1 != null || head2 != null){
// 首先加进位(result是初始值)
int result = carry;
// 判断head1
if(head1 != null){
result += head1.val;
head1 = head1.next;
}
// 判断head2
if(head2 != null){
result += head2.val;
head2 = head2.next;
}
// 运算并赋值
carry = result / 10;
fllowHead.next = new ListNode(result % 10);
fllowHead = fllowHead.next;
}
// 当双链走完,仍有进位,需要加上
if(carry == 1){
fllowHead.next = new ListNode(1);
}
return reverse(head.next);
}
// 反转链表
public ListNode reverse(ListNode head){
if(head == null){
return null;
}
ListNode preNode = null;
ListNode nextNode = null;
while(head != null){
nextNode = head.next;
head.next = preNode;
preNode = head;
head = nextNode;
}
return preNode;
}
// 输出函数,调试
public void printList(ListNode head){
while(head != null){
System.out.println(head.val);
}
}
}

