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) {
// write code here
head1 = ReverseList(head1);
head2 = ReverseList(head2);
ListNode t1 = head1, t2 = head2;
ListNode result = null; // 头指针
ListNode res_tail = null;
int cin = 0;
while (t1 != null || t2 != null) {
int count = 0;
if (t1 != null) {
count += t1.val;
t1 = t1.next;
}
if (t2 != null) {
count += t2.val;
t2 = t2.next;
}
count += cin;
ListNode t = new ListNode(count % 10);
cin = count / 10;
if (result == null) {
result = t;
res_tail = result;
}
else {
res_tail.next = t;
res_tail = res_tail.next;
}
}
if (cin > 0)
res_tail.next = new ListNode(cin);
return ReverseList(result);
}
public ListNode ReverseList(ListNode head) {
if (head == null || head.next == null){
return head;
}
ListNode r = head.next;
ListNode l = head;
ListNode t = r.next;
head.next = null;
while(t != null) {
r.next = l;
l = r;
r = t;
t = r.next;
}
r.next = l;
return r;
}
}
主要是链表先反转,直接copy的前几个题的,反转后for循环长链做加法,记录进位cin,最后反转输出列表