思路:
1.两数相加肯定是先个位相加,然后进位
2.反转链表,链表头就是个位数字了,然后相加,相加后,商的值就是当前节点值,余数参数下一个节点计算进位。(因为可能最后一个节点是0,所以反转后的到的节点,如果头节点是0的话,就要去掉。看你怎么写了,因为在所有节点计算完后,余数可能为0,也可能非0,需要新建个节点来存储,如果是0的话,那计算完,反转后,最高位不能是0)
3.当然,没有链表是以0开头的节点,0开头的正数怎么可能,如果你担心的话,那可以遍历头节点去除值为0的,知道下一个值不为0的节点。
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode head1, ListNode head2) {
// write code here
if(head1 == null && head2 == null){
return null;
}
if(head1 == null){
return head2;
}
if(head2 == null){
return head1;
}
head1 = reverse(head1);
head2 = reverse(head2);
//开始从最右侧 个位相加了
int addition = 0;
ListNode head = new ListNode(-1);
ListNode current = head;
while(head1 != null || head2 != null){
int a = 0, b = 0;
if(head1 != null){
a = head1.val;
head1 = head1.next;
}
if(head2 != null){
b = head2.val;
head2 = head2.next;
}
int sum = addition + a + b;
current.val = sum % 10;
addition = sum / 10;
ListNode next = new ListNode(-1);
current.next = next;
current = next;
}
current.val = addition;
head = reverse(head);
if(head.val == 0){
head = head.next;
}
return head;
}
private ListNode reverse(ListNode head){
ListNode cur = head;
ListNode pre = null;
while(cur != null){
ListNode temp = cur.next;
cur.next = pre;
pre = cur;
cur = temp;
}
return pre;
}
}