62,615
社区成员
发帖
与我相关
我的任务
分享
public Node addList2(Node head1,Node head2)
{
Stack<Integer> stack1 = new Stack<Integer>();
Stack<Integer> stack2 = new Stack<Integer>();
while(head1 != null){
stack1.push(head1.data);
head1 = head1.next;
}
while(head2 != null){
stack2.push(head2.data);
head2 = head2.next;
}
int n1=0; //链表1的数值
int n2=0; //链表2的数值
int n=0; //n1+n2+ca
int ca=0; //进位
Node node=null; //当前节点
Node pnode=null; //当前节点的前驱节点
while(!stack1.isEmpty()||!stack2.isEmpty())
{
n1 = stack1.isEmpty() ? 0 : stack1.pop();
n2 = stack2.isEmpty() ? 0 : stack2.pop();
n=n1+n2+ca;
node=new Node(n%10);
node.next=pnode;//根据下一行代码,node节点next域指向它自身,为什么要指向自身
pnode=node;//
ca=n/10;
}
if(ca == 1)
{
pnode = node;
node=new Node(n/10);
node.next=pnode;//问题同上
}
return node;
}