解题思路:直接使用栈,将每个节点的值先保存,然后一个个弹出计算的进位数val3,,将结果一个个在压入栈stack3,,最后一个个弹出
时间复杂度O(n),空间复杂度为O(n)
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
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
Stack<Integer> stack1 = new Stack<>();
Stack<Integer> stack2 = new Stack<>();
Stack<Integer> stack3 = new Stack<>();
while (head1 != null) {
stack1.push(head1.val);
head1 = head1.next;
}
while (head2 != null) {
stack2.push(head2.val);
head2 = head2.next;
}
int val1 = 0, val2 = 0, val3 = 0, val4 = 0;
while (!stack1.isEmpty() && !stack2.isEmpty()) {
val1 = stack1.pop();
val2 = stack2.pop();
val4 = (val1 + val2 + val3) % 10;
stack3.push(val4);
val3 = (val1 + val2 + val3) / 10;
}
while (!stack1.isEmpty()) {
val1 = stack1.pop();
val4 = (val1 + val3) % 10;
stack3.push(val4);
val3 = (val1 + val3) / 10;
}
while (!stack2.isEmpty()) {
val2 = stack2.pop();
val4 = (val2 + val3) % 10;
stack3.push(val4);
val3 = (val2 + val3) / 10;
}
if (val3 != 0) {
stack3.push(val3);
}
ListNode pre = new ListNode(-1);
ListNode result = pre;
while (!stack3.isEmpty()) {
ListNode node = new ListNode(stack3.pop());
pre.next = node;
pre = pre.next;
}
return result.next;
}
}