两个链表生成相加链表
两个链表生成相加链表
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b?tpId=196&tab=answerKey
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
Stack<ListNode> stack1=new Stack<>();//用栈保存链表 便于从链表尾部相加
Stack<ListNode> stack2=new Stack<>();
while (head1!=null){
stack1.push(head1);
head1=head1.next;
}
while (head2!=null){
stack2.push(head2);
head2=head2.next;
}
int jw=0;//初始化进位为0 后续不断更新
ListNode pre=new ListNode(0);
pre.next=null;
while (stack1.size()>0 && stack2.size()>0){
int p1=stack1.pop().val;
int p2=stack2.pop().val;
int rr =(p1+p2+jw)%10;
jw=(p1+p2+jw)/10;
ListNode temp=new ListNode(0);
temp.val=rr;
temp.next=pre.next;
pre.next=temp;
}
//stack jw pre
jw=tj(stack1,jw,pre);
jw=tj(stack2,jw,pre);
if (jw!=0) {
ListNode t=new ListNode(0);
t.val=jw;
t.next=pre.next;
pre.next=t;
}
return pre.next;
}
private int tj(Stack<ListNode> stack1, int jw, ListNode pre) {
while (stack1.size()>0){
int p1=stack1.pop().val;
int rr = (p1+jw)%10;
jw=(p1+jw)/10;
ListNode temp=new ListNode(0);
temp.val=rr;
temp.next=pre.next;
pre.next=temp;
}
return jw;
}
腾讯公司福利 1143人发布