You are given two non-empty linked lists representing two non-negative integers. 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.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.
难度:Medium
解析:显然这个需要同步的将两个链表进行对应节点的循环相加,直至两个链表均无节点,且无进位,否则继续进行循环。不过,在循环相加的时候需要注意各种异常情况,如两链表长短不一,或者进位问题,导致循环结束的时机不同。
方法一:穷举遍历(★★★)
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode p = new ListNode(0);
ListNode result = p;
int isAdd = 0;
while(l1 != null || l2 != null || isAdd != 0){
int temp = (l1 != null ? l1.val : 0) + (l2 != null ? l2.val : 0) + isAdd;
ListNode node = new ListNode(temp%10);
p.next = node;
p = node;
isAdd = temp/10;
if(l1 != null){
l1 = l1.next;
}
if(l2 != null){
l2 = l2.next;
}
}
return result.next;
}
}
结果:Runtime:42 ms,beats 20.69% of Java submission.
备注:遍历两个链表,直至两个量表均无节点且无进位,时间复杂度O(n)。