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
思路:
1. 如何对齐?由于reverse order,所以最左边的是最低位,所以直接加,然后把每一位的进位加到高位即可!操作linked list. 看是否会改变头节点。还需考虑是否最高位有进位!
2. 是完全产生新的list?还是把结果加在其中某一个list上?如何知道每个list的长度?
3. 下面的方法是:完全产生一个新的List,比较trival,所以需要很小心!
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//
ListNode* l=new ListNode(0);
ListNode* cur=l;
int carry=0;
while(l1||l2||carry){
int sum=(l1?l1->val:0)+(l2?l2->val:0)+carry;
carry=sum/10;
sum=sum%10;
cur->val=sum;
l1=l1?l1->next:NULL;
l2=l2?l2->next:NULL;
if(l1||l2||carry)
cur->next= new ListNode(0);
cur=cur->next;
}
return l;
}
};