Description
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.
Solution:
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode temp1 = l1;
ListNode temp2 = l2;
ListNode res = null;
ListNode fin = null;
int prev = 0;
while(temp1 != null || temp2 != null || prev != 0) {
int temp = (temp1 == null ? 0 : temp1.val) + (temp2 == null ? 0 : temp2.val);
temp = temp + prev;
ListNode p = null;
if (temp >= 10) {
p = new ListNode(temp - 10);
prev = 1;
} else {
p = new ListNode(temp);
prev = 0;
}
if (res == null) {
res = p;
fin = p;
} else {
res.next = p;
}
res = p;
temp1 = temp1 == null ? null : temp1.next;
temp2 = temp2 == null ? null : temp2.next;
}
return fin;
}
}
Attentions
这道题思路很简单,其实就是数学中数字相加的基本原理,链表从左向右遍历,实际上就是从低位遍历到高位,小学数学,低位相加和大于等于10,需要向上进一位,考虑到两个链表长度可能不一致,需要进行判空
SubMissions
Runtime:20 ms, faster than 82.57% of Java online submissions for Add Two Numbers.
Memory Usage:48.3 MB, less than 9.84% of Java online submissions for Add Two Numbers.
说明 速度仍然有优化的空间,同时内存占用稍高
重新分析占用:
思考使用递归的方法进行求和
submission.png
网友评论