题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
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
Stack<ListNode> st1 = new Stack<>();
Stack<ListNode> st2 = new Stack<>();
ListNode start = new ListNode(-1);
while (head1 != null) {
st1.add(head1);
head1 = head1.next;
}
while (head2 != null) {
st2.add(head2);
head2 = head2.next;
}
int jinwei = 0;
while (!st1.isEmpty() && !st2.isEmpty()) {
int nodeVal = st1.pop().val + st2.pop().val + jinwei;
jinwei = nodeVal / 10;
ListNode temp = new ListNode(nodeVal % 10);
temp.next = start.next;
start.next = temp;
}
while (!st1.isEmpty()) {
int nodeVal = st1.pop().val + jinwei;
jinwei = nodeVal / 10;
ListNode temp = new ListNode(nodeVal % 10);
temp.next = start.next;
start.next = temp;
}
while (!st2.isEmpty()) {
int nodeVal = st2.pop().val + jinwei;
jinwei = nodeVal / 10;
ListNode temp = new ListNode(nodeVal % 10);
temp.next = start.next;
start.next = temp;
}
return start.next;
}
}
我是利用了栈。如果没其他性能要求的话,这样还是最稳妥的。

