思路分析:正序不好相加,正难则反,我们就将链表反转,进行相加即可
1.反转链表
2.如何链表1和链表2不为空就相加,为空 + 0和不想加是等价,只需一个变量分别相加即可,这个变量也可以表示进位,如果进位就将这个变量设置成1进行下次相加,如果不进位就设置为0,进行下次相加
3.将最后的结果反转
public ListNode addInList(ListNode head1, ListNode head2) {
//1.逆序链表
head1 = reserveNode(head1);
head2 = reserveNode(head2);
int temp = 0;//记录进位 和 临时值
ListNode ret = new ListNode(0),
prev = ret; //虚拟节点 和 返回链表的移动指针
while(head1 != null || head2 != null || temp != 0){//三个条件均为0,结束循环
//2.按位相加,不加和+0同理
if (head1 != null) {
temp += head1.val;
head1 = head1.next;
}
if (head2 != null) {
temp += head2.val;
head2 = head2.next;
}
//3.记录进位和ret添加个位
prev = prev.next = new ListNode(temp % 10);
temp /= 10;//记录进位
}
return reserveNode(ret.next);
}
//反转链表
public ListNode reserveNode(ListNode cur) {
ListNode newHead = new ListNode(0);//创建虚拟头节点
while (cur != null) {
ListNode next = cur.next;//记录防止对cur操作,而找不到下一个位置了
cur.next = newHead.next;
newHead.next = cur;
cur = next;
}
return newHead.next;
}
扩展一题吧,其实上面这个题,就是利用下面题的思维,只不过是在链表中进行的
public String solve(String s, String t) {
StringBuilder result = new StringBuilder();
int temp = 0;//标记进位 + 累加结果
int i = s.length() - 1, j = t.length() - 1;
while(i != 0 || j != 0 || temp != 0){
if (i >= 0) temp += s.charAt(i--) - '0';
if (j >= 0) temp += t.charAt(j--) - '0';
result.append((char)('0' + temp % 10));
temp /= 10;
}
return result.reverse().toString();//逆序
}