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
这个方法就是将链表中的数字串起来,当做一个long,例如2->4->5,可以根据题目具体要求转化成long型的245或542,再做后续的操作,就很容易了。举一反三,链表数字的反序也可以采用这个方法。
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public Long listTOLong(ListNode l){
long num = 0;
long temp =1;
int i=0;
while(l!=null){
num = num+l.val*temp;
temp=temp*10;
l=l.next;
}
return num;
}
public ListNode longToList(Long num){
ListNode l3 = new ListNode(-1);
l3.next = null;
ListNode c = l3;
c.val=(int)(num%10);
num = num/10;
while(num>0){
ListNode cnext = new ListNode((int)(num%10));
cnext.next=null;
c.next=cnext;
num = num/10;
c=c.next;
}
return l3;
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if(l1==null&&l2==null){
return null;
}
//链表转long型
long num1 = listTOLong(l1);
long num2 = listTOLong(l2);
//System.out.println("l1:"+num1+" l2:"+num2);
long num3 = num1+num2;
//System.out.println("l3:"+num3);
//long型转链表
ListNode l3 = longToList(num3);
return l3;
}
}