题目描述:
给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。
如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。
您可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
package op;
public class Solution {
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public void to(ListNode l) {
ListNode s=l;
String a="";
while(s!=null) {
a=a+s.val;
s=s.next;
}
StringBuffer buffer=new StringBuffer(a);
System.out.println(buffer.reverse());
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode res=new ListNode(0),resq=res;;
ListNode p=l1,q=l2;
int carry=0;
while(p!=null||q!=null) {
int i=(p!=null)?p.val:0;