题解 | 链表相加(二)
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
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) {
Stack<ListNode> stack1 = new Stack<>();
Stack<ListNode> stack2 = new Stack<>();
Stack<ListNode> result = new Stack<>();
while (head1 != null) {
stack1.push(head1);
head1 = head1.next;
}
while (head2 != null) {
stack2.push(head2);
head2 = head2.next;
}
boolean temp = false;
while (!stack1.empty() || !stack2.empty()) {
ListNode node1 = stack1.empty() ? new ListNode(0) : stack1.pop();
ListNode node2 = stack2.empty() ? new ListNode(0) : stack2.pop();
int tempSum = node1.val + node2.val + (temp ? 1 : 0);
temp = tempSum >= 10;
result.push(new ListNode(tempSum % 10));
}
if (temp) {
result.push(new ListNode(1));
}
ListNode res = new ListNode(0);
ListNode head = res;
while (!result.empty()) {
head.next = result.pop();
head = head.next;
}
return res.next;
}
}

查看3道真题和解析