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
// 定一个临时链表
ListNode temp = new ListNode(-1);
head1 = reversalList(head1);
head2 = reversalList(head2);
// 尾节点
ListNode tempTail = temp;
// 临时个位置
int res = 0;
while(head1 != null || head2 != null) {
int sum = res;
if (head1 != null) {
sum = sum + head1.val;
head1 = head1.next;
}
if (head2 != null) {
sum = sum + head2.val;
head2 = head2.next;
}
res = sum / 10;
int val = sum % 10;
ListNode node = new ListNode(val);
tempTail.next = node;
tempTail = tempTail.next;
}
if (res > 0) {
ListNode node = new ListNode(res);
tempTail.next = node;
}
return reversalList(temp.next);
}
public ListNode reversalList(ListNode head) {
// 定一个栈, 将head1进行反转
Stack<ListNode> stack = new Stack<>();
while (head != null) {
stack.push(head);
head = head.next;
}
// 出栈
head = stack.pop();
ListNode cur = head;
while (!stack.isEmpty()) {
ListNode node = stack.pop();
node.next = null;
cur.next = node;
cur = cur.next;
}
return head;
}
}