题解 | #链表相加(二)#
链表相加(二)
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
if (head1 == null) {
return head2;
}
if (head2 == null) {
return head1;
}
//使用栈存储两个链表数据,然后计算
Stack<ListNode> s1 = new Stack<>();
Stack<ListNode> s2 = new Stack<>();
ListNode p = head1, q = head2;
while (p != null) {
s1.push(p);
p = p.next;
}
while (q != null) {
s2.push(q);
q = q.next;
}
int flag = 0;
if (s1.size() >= s2.size()) {
p = caculateList(s1, s2);
} else {
p = caculateList(s2, s1);
}
return p;
}
//用于计算,个人感觉代码冗余,却无计可施
private static ListNode caculateList(Stack<ListNode> s1,Stack<ListNode> s2){
int flag=0;
ListNode node=null;
while (s1.size()>0 && s2.size()>0){
node=s1.pop();
node.val=node.val+s2.pop().val+flag;
flag=node.val/10;
node.val=node.val%10;
}
while (s1.size()>0){
node=s1.pop();
node.val=node.val+flag;
flag=node.val/10;
node.val=node.val%10;
}
if (flag>0){
ListNode node1=new ListNode(flag);
node1.next=node;
node=node1;
}
return node;
}
}
查看12道真题和解析