题目:
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.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
思路:
其实本题很简单,主要就是要考虑周全。同时可能有些人会想为什么不把他转成数字直接计算再转成linked list。 我个人认为主要原因就是第一他这个数字是倒序的单向指针如果做转换必须遍历两次,所以效率要比正规思路差。
其次要注意的点主要有
1、数字加完之后要考虑到进位 也就是carry, 两个list 都加完了 也得考虑最后carry 是否为0, 不为0 得再单加一个节点给carry
2、题目有点诱导 好像两个list 是一样长的,但其实两个list 很可能不一样长,于是在便利完最小的那个时还需要考虑拎一个是否还得继续带着之前得的carry 继续进行加法。
3、这个题最好的是在loop里进行添加node,这样就涉及到应该把第一个节点想成一个dummy node 即 fakehead,这样最后返回fakehead.next 就是咱们需要的头结点。
代码:
/**
* 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) {
int carry = 0;
int sum = 0;
int tmp = 0;
ListNode cur1 = l1;
ListNode cur2 = l2;
ListNode fakehead = new ListNode(0);
ListNode tmpNode = fakehead;
while(cur1 != null && cur2 != null){
sum = cur1.val + cur2.val + carry;
carry = sum /10;
tmp = sum % 10;
tmpNode.next = new ListNode(tmp);
tmpNode = tmpNode.next;
cur1 = cur1.next;
cur2 = cur2.next;
}
if(cur1 != null) {
while(cur1 != null){
sum = cur1.val + carry;
carry = sum/10;
tmp = sum %10;
tmpNode.next = new ListNode(tmp);
tmpNode = tmpNode.next;
cur1 = cur1.next;
}
}
if (cur2 != null) {
while(cur2 != null){
sum = cur2.val + carry;
carry = sum/10;
tmp = sum %10;
tmpNode.next = new ListNode(tmp);
tmpNode = tmpNode.next;
cur2 = cur2.next;
}
}
if(carry != 0)
tmpNode.next = new ListNode(carry);
return fakehead.next;
}
}