题解 | #链表相加(二)#
链表相加(二)
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> stack1 = new Stack<ListNode>();
Stack<ListNode> stack2 = new Stack<ListNode>();
Stack<ListNode> stack = new Stack<ListNode>();
int value = 0;
int flag = 0;
ListNode head = null;
ListNode temp = null;
boolean b = true;
while(head1 != null){
stack1.push(head1);
head1 = head1.next;
}
while(head2 != null){
stack2.push(head2);
head2 = head2.next;
}
while(!stack1.isEmpty() && !stack2.isEmpty()){
value = stack1.pop().val + stack2.pop().val;
stack.push(new ListNode((value + flag)%10));
flag = (value+flag) / 10;
}
while(!stack1.isEmpty()){
value = stack1.pop().val + flag;
stack.push(new ListNode(value%10));
flag = value/10;
}
while(!stack2.isEmpty()){
value = stack2.pop().val + flag;
stack.push(new ListNode(value%10));
flag = value/10;
}
while(!stack.isEmpty()){
if(b){
head = stack.pop();
temp = head;
b = false;
continue;
}
temp.next = stack.pop();
temp = temp.next;
}
return head;
}
}
查看24道真题和解析