import org.w3c.dom.NodeList;
public class Solution2 {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyhead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyhead;
int addOne = 0;
//考虑validation
while (p == null || q == null || curr == null) {
return null;
}
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = addOne + x + y;
addOne = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) {
p = p.next;
}
if (q != null) {
q = q.next;
}
if (addOne > 0) {
curr.next = new ListNode(addOne);
}
}
return dummyhead.next;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static String print(ListNode l){
StringBuilder builder=new StringBuilder();
while(l!=null){
builder.append(l.val);
l=l.next;
}
return builder.toString();
}
/**
* @测试部分
*/
public static void main(String args[]) {
ListNode l1=new ListNode(2);
ListNode l2=new ListNode(5);
l1.next=new ListNode(4);
l2.next=new ListNode(6);
l1.next.next=new ListNode(3);
l2.next.next=new ListNode(4);
System.out.println(print(addTwoNumbers(l1,l2)));
}
}
import org.w3c.dom.NodeList;
public class Solution2 {
public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode dummyhead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyhead;
int addOne = 0;
//考虑validation
while (p == null || q == null || curr == null) {
return null;
}
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = addOne + x + y;
addOne = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) {
p = p.next;
}
if (q != null) {
q = q.next;
}
if (addOne > 0) {
curr.next = new ListNode(addOne);
}
}
return dummyhead.next;
}
static class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
public static String print(ListNode l){
StringBuilder builder=new StringBuilder();
while(l!=null){
builder.append(l.val);
l=l.next;
}
return builder.toString();
}
/**
* @测试部分
*/
public static void main(String args[]) {
ListNode l1=new ListNode(2);
ListNode l2=new ListNode(5);
l1.next=new ListNode(4);
l2.next=new ListNode(6);
l1.next.next=new ListNode(3);
l2.next.next=new ListNode(4);
System.out.println(print(addTwoNumbers(l1,l2)));
}
}