You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
解决方法(java版)
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
List<ListNode> list=new LinkedList<ListNode>();
int valuenext=0;
while(l1!=null&&l2!=null){
int value=(valuenext+l1.val+l2.val)%10;
//valuenext=0;
valuenext=(l1.val+l2.val+valuenext)/10;
list.add(new ListNode(value));
l1=l1.next;
l2=l2.next;
}
if(l1==null&&l2!=null){
while(l2!=null){
int value=(valuenext+l2.val)%10;
valuenext=(l2.val+valuenext)/10;
list.add(new ListNode(value));
l2=l2.next;
}
}
else if(l2==null&&l1!=null){
while(l1!=null){
int value=(valuenext+l1.val)%10;
valuenext=(l1.val+valuenext)/10;
list.add(new ListNode(value));
l1=l1.next;
}
}
if(valuenext!=0&&l1==null&&l2==null){
list.add(new ListNode(valuenext));
}
for(int i=0;i<list.size()-1;i++){
list.get(i).next=list.get(i+1);
}
return list.get(0);
}
}