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
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode ln1, head;
int flag = 0;
head = ln1 = new ListNode(0);
while (l1 != null || l2 != null) {
if (l1 != null && l2 != null) {
if (l1.val + l2.val + flag >= 10) {
ln1.val = l1.val + l2.val + flag - 10;
flag = 1;
} else {
ln1.val = l1.val + l2.val + flag;
flag = 0;
}
l1 = l1.next;
l2 = l2.next;
} else if (l1 == null) {
if (l2.val + flag >= 10) {
ln1.val = l2.val + flag - 10;
flag = 1;
} else {
ln1.val = l2.val + flag;
flag = 0;
}
l2 = l2.next;
} else if (l2 == null) {
if (l1.val + flag >= 10) {
ln1.val = l1.val + flag - 10;
flag = 1;
} else {
ln1.val = l1.val + flag;
flag = 0;
}
l1 = l1.next;
}
if (l1 != null || l2 != null)
ln1.next = new ListNode(0);
if (flag == 1) {
ln1.next = new ListNode(0);
ln1.next.val = 1;
}
ln1 = ln1.next;
}
return head;
}
这是我写的,虽然通过了但是我觉得还可以提高,点了一下看到了一个别人写程序,亮瞎我眼了。
/**
* 很简便的一个写法,至少甩我两条街
* @param l1
* @param l2
* @return
*/
public ListNode addTwoNumbers2(ListNode l1, ListNode l2) {
ListNode dummyHead = new ListNode(0);
ListNode p = l1, q = l2, curr = dummyHead;
int carry = 0;
while (p != null || q != null) {
int x = (p != null) ? p.val : 0;
int y = (q != null) ? q.val : 0;
int sum = carry + x + y;
carry = sum / 10;
curr.next = new ListNode(sum % 10);
curr = curr.next;
if (p != null) p = p.next;
if (q != null) q = q.next;
}
if (carry > 0) {
curr.next = new ListNode(carry);
}
return dummyHead.next;
}