題目
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
分析
解答
/**
* 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* m=l1;
ListNode* n=l2;
ListNode* result=new ListNode(0);
ListNode* cur=result;
int carry=0;
int sum=0;
while(m!=NULL || n!=NULL){
if(m==NULL) {
m=new ListNode(0);
}
if(n==NULL) {
n=new ListNode(0);
}
sum=(m->val)+(n->val)+carry;
carry=sum/10;
//cout<<carry<<" "<<sum<<endl;
cur->next=new ListNode(sum%10);
cur=cur->next;
if(m!=NULL) m=m->next;
if(n!=NULL) n=n->next;
sum=0;
}
if(carry>0){
cur->next=new ListNode(carry);
}
return result->next;
}
};
不難得出,該算法的複雜度爲O(max{l1.size(), l2.size()})