题目
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
思路
很简单,就是对应位置相加,大于等于10的就进位,不过一开始还是犯了一些错误导致时间比较慢,只打败了4%的人。。。主要原因是对next操作,这样就无形多了一些时间。又增加了一个辅助变量p,时间增快了很多打败了80%的人。我这样其实是把最终长度遍历两遍。如果放到一个循环遍历一遍应该还可以增加速度。但是那样代码看起来太复杂了,不便于理解。这样,前面的两个循环做相加,后边一个循环做进位的整理。比较清晰。
解法
/**
* 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) {
ListNode head = l1 ,p = l1;
while (null != l1 && null != l2) {
l1.val = l1.val + l2.val ;
p = l1 ;
l1 = p.next ;
l2 = l2.next ;
}
while(null != l2){
p.next = new ListNode(l2.val);
l2 = l2.next ;
p = p.next ;
}
l1 = head ;
while(null!=l1){
if (l1.next == null) {
l1.next = l1.val>=10 ? new ListNode(1):null ;
}else {
l1.next.val = l1.val/10+l1.next.val;
}
l1.val = l1.val%10;
l1 = l1.next;
}
return head ;
}
}