链接:链表相加(二)_牛客题霸_牛客网 (nowcoder.com)
分析:
算法原理是逆序+高精度算法
逆序的原因是为了实现从低位(个位)开始相加。
public class Solution {
//逆序链表
public ListNode reverse(ListNode head){
ListNode newHead = new ListNode(0);
ListNode cur = head;
while(cur != null){
ListNode next = cur.next;
cur.next = newHead.next;
newHead.next = cur;
cur = next;
}
return newHead.next;
}
public ListNode addInList (ListNode head1, ListNode head2) {
//调用reverse()方法,以便从低位相加
head1 = reverse(head1);
head2 = reverse(head2);
ListNode cur1 = head1;
ListNode cur2 = head2;
//t用来存储进位
int t = 0;
//ret作为头节点,prev初始化ret作为最终结果链表
ListNode ret = new ListNode(0);
ListNode prev = ret;
while(cur1 != null || cur2 != null || t != 0){
if(cur1 != null){
t += cur1.val;
cur1 = cur1.next;
}
if(cur2 != null){
t += cur2.val;
cur2 = cur2.next;
}
prev = prev.next = new ListNode(t % 10);
t /= 10;
}
return reverse(ret.next);
}
}