![在这里插入图片描述](https://img-blog.csdnimg.cn/15ee26f780dc44baa1d40d12d938b499.png)
思路
:先反转两个链表然后依次进行值相加并建立新节点连接到结果链表中,最后反转结果链表即可.
解法1
public class Solution {
public ListNode addInList (ListNode head1, ListNode head2) {
if(head1 == null && head2 == null){
return null;
}
if(head1 == null){
return head2;
}
if(head2 == null){
return head1;
}
ListNode p1 = reverse(head1);
ListNode p2 = reverse(head2);
int approve = 0;
int val = 0;
ListNode ret = new ListNode(1);
ListNode cur = ret;
while(p1 != null && p2 != null){
val = (p1.val + p2.val + approve) % 10;
approve = (p1.val + p2.val + approve) / 10;
cur.next = new ListNode(val);
cur = cur.next;
p1 = p1.next;
p2 = p2.next;
}
while(p1 != null){
val = (p1.val + approve) % 10;
approve = (p1.val + approve) / 10;
cur.next = new ListNode(val);
cur = cur.next;
p1 = p1.next;
}
while(p2 != null){
val = (p2.val + approve) % 10;
approve = (p2.val + approve) / 10;
cur.next = new ListNode(val);
cur = cur.next;
p2 = p2.next;
}
if(approve == 1){
cur.next = new ListNode(1);
}
return reverse(ret.next);
}
public ListNode reverse(ListNode head){
ListNode cur = head;
ListNode prev = null;
while(cur != null){
ListNode nextNode = cur.next;
cur.next = prev;
prev = cur;
cur = nextNode;
}
return prev;
}
}
解法2
public class Solution {
public ListNode addInList (ListNode head1, ListNode head2) {
Stack<Integer> stack1=new Stack();
Stack<Integer> stack2=new Stack();
int cnt=0;
int sum=0;
ListNode dummy=new ListNode(0);
while(head1!=null){
stack1.add(head1.val);
head1=head1.next;
}
while(head2!=null){
stack2.add(head2.val);
head2=head2.next;
}
while(!stack1.isEmpty()||!stack2.isEmpty()||cnt>0){
int c=!stack1.isEmpty()?stack1.pop():0;
int d=!stack2.isEmpty()?stack2.pop():0;
sum=(c+d+cnt)%10;
cnt=(c+d+cnt)/10;
ListNode node=new ListNode(sum);
node.next=dummy.next;
dummy.next=node;
}
return dummy.next;
}
}