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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
if (l1 == null)
return l2;
if (l2 == null) //这题看起来简单,但是花了很长时间啊,链表要遍历几次,但是这样写代码最短?实在不想再写了
return l1;
int temp = 0;
ListNode p = l1;
ListNode q = l2;
ListNode longList = l1;
ListNode la = l1;
while (p != null && q != null) {
p = p.next;
q = q.next;
}
if (q == null) {
q = l1;
p = l2;
longList = l1;
} else {
q = l2;
p = l1;
longList = l2;
}
while (p != null && q != null) {
if (p.val + q.val + temp >= 10) {
q.val = p.val + q.val + temp - 10;
temp = 1;
} else {
q.val = q.val + p.val + temp;
temp = 0;
}
p = p.next;
q = q.next;
}
while (q != null) {
if (q.val + temp >= 10) {
q.val = q.val + temp - 10;
temp = 1;
} else {
q.val = q.val + temp;
temp = 0;
}
q = q.next;
}
if (temp == 1) {
ListNode last = new ListNode(1);
last.next = null;
p = longList;
while (p.next!= null)
p = p.next;
la = p;
la.next = last;
} return longList;
}
}