import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* public ListNode(int val) {
* this.val = val;
* }
* }
*/
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
head1 = reverse(head1);
head2 = reverse(head2);
ListNode dummy = new ListNode(-1);
ListNode cur = dummy;
int add = 0;
while (head1 != null || head2 != null) {
int x = head1 == null ? 0 : head1.val;
int y = head2 == null ? 0 : head2.val;
if(head1 != null)head1 = head1.next;
if(head2 != null)head2 = head2.next;
int sum = x + y + add;
cur.next = new ListNode(sum % 10);
cur = cur.next;
add = sum / 10;
}
if (add != 0)
cur.next = new ListNode(add);
return reverse(dummy.next);
}
private ListNode reverse(ListNode head) {
ListNode pre = null, cur = head, next = null;
while (cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}
先翻转链表,才能从低位开始相加,最后结果需要翻转

京公网安备 11010502036488号