思路
这道题我大概看了下, 没什么特别的感觉啊, 首先既然list中的digit是倒序存放的, 也就是从头部开始一次表示个位, 十位, 百位... 这样的话就简单了, 直接按照加过去, 只需要O(n)的时间.
实现
具体实现上, 也没什么, 就是不断地对于list进行循环然后直至到底list末尾, 要注意的是list可能不等长, 还有如果在两个list都到达末尾的情况下累加器里面还有值(上一次计算有进位), 那么还需要再添加一个node.
提交
这次是一次AC
代码
里面有一些我自己写的测试代码.
/**
* Definition for singly-linked list.
*/
public class Solution {
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
ListNode re = null, cur = null;
int adder = 0;
while(l1 != null && l2 != null){
int sum = l1.val + l2.val + adder;
int digit = sum % 10;
adder = sum / 10;
if(re == null){
re = new ListNode(digit);
cur = re;
}
else{
cur.next = new ListNode(digit);
cur = cur.next;
}
l1 = l1.next;
l2 = l2.next;
}
ListNode l3 = l1 == null ? l2 : l1;
while(l3 != null){
int sum = l3.val + adder;
int digit = sum % 10;
adder = sum / 10;
if(re == null){
re = new ListNode(digit);
cur = re;
}
else{
cur.next = new ListNode(digit);
cur = cur.next;
}
l3 = l3.next;
}
if(adder != 0){
cur.next = new ListNode(adder);
}
return re;
}
private ListNode getNode(int[] list){
if(list.length == 0) return null;
ListNode re = new ListNode(list[0]);
ListNode cur = re;
for(int i = 1; i < list.length; ++i){
cur.next = new ListNode(list[i]);
cur = cur.next;
}
return re;
}
public static void main(String[] args) {
Solution solution = new Solution();
ListNode l1 = solution.getNode(new int[]{2, 4, 3});
ListNode l2 = solution.getNode(new int[]{5, 6, 0});
ListNode l3 = solution.addTwoNumbers(l1, l2);
while(l3 !=null){
System.out.println(l3.val);
l3 = l3.next;
}
}
}
最佳实现
这道题基本上没什么优化了, 但是代码上还可以写得更整洁, 第一个while其实也能写到第二个while里面, 这里有一份样例代码 :
public ListNode addTwoNumbers(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;
}