题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
public static ListNode addInList(ListNode head1, ListNode head2) { // write code here Stack stack1 = new Stack<>(); while (head1 != null) { stack1.push(head1.val); head1 = head1.next; } Stack stack2 = new Stack<>(); while (head2 != null) { stack2.push(head2.val); head2 = head2.next; }
ListNode newNode = new ListNode(-1);
ListNode nowNode = newNode;
int yu = 0;
while (stack1.size() > 0 || stack2.size() > 0) {
int temp = yu;
if (stack1.size() > 0) {
temp += stack1.pop();
}
if (stack2.size() > 0) {
temp += stack2.pop();
}
if (temp >= 10) {
yu = 1;
temp = temp % 10;
} else {
yu = 0;
}
nowNode.next = new ListNode(temp);
nowNode = nowNode.next;
}
if (yu == 1) {
nowNode.next = new ListNode(1);
}
nowNode = reverse(newNode.next);
return nowNode;
}
private static ListNode reverse(ListNode now) {
ListNode pre = null;
while (now != null) {
ListNode next = now.next;
now.next = pre;
pre = now;
now = next;
}
return pre;
}