题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
import java.util.*;
/*
* 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) {
// 先将链表反转,低位在前:1000->0001
ListNode r1 = reverse(head1);
ListNode r2 = reverse(head2);
int jw = 0; // 进位
ListNode result = null;
while(r1!=null || r2!=null){ // 从低位开始相加
int v1 = r1==null?0: r1.val;
int v2 = r2==null?0: r2.val;
int sum = v1 + v2 + jw;
ListNode newNode = new ListNode(sum%10);
newNode.next = result;
result = newNode;
jw = sum/10; // 计算进位
if(r1!=null) r1 = r1.next;
if(r2!=null) r2 = r2.next;
}
if(jw>0){ // 如果最后还有进位
ListNode newNode = new ListNode(jw);
newNode.next = result;
result = newNode;
}
return result;
}
/**
* 反转链表
*/
private ListNode reverse(ListNode head){
ListNode pre = null;
while(head!=null){
ListNode next = head.next;
head.next = pre;
pre = head;
head = next;
}
return pre;
}
}