题解 | #链表相加(二)#
链表相加(二)
http://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
/*
* 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
LinkedList<Integer> l1 = new LinkedList<>();
LinkedList<Integer> l2 = new LinkedList<>();
putData(l1,head1);
putData(l2,head2);
ListNode Node = null;
ListNode cur = null ;
int carry = 0;
while(!l1.isEmpty() || !l2.isEmpty() || carry != 0){
int x , y ,sum ;
if(!l1.isEmpty()){
x = l1.pop();
}else{
x = 0;
}
if(!l2.isEmpty()){
y = l2.pop();
}else{
y = 0;
}
sum = x + y + carry ;
carry = sum / 10;
sum %= 10 ;
cur = new ListNode(sum);
cur.next = Node ;
Node = cur ;
}
return Node ;
}
public void putData(LinkedList<Integer> s1 , ListNode head){
if (s1 == null ) s1 = new LinkedList();
while(head != null) {
s1.push(head.val);
head = head.next ;
}
}
}