首先,空间为O(1),因为需要空间为O(1)也就是说只有在最后进位还有但是链表已经没有了才能创建node。思路大概就是,设置值用一个链表,然后先将两个已有的节点相加。然后出来后只需要处理多余的节点和carry。注意边界节点。
code
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
//试试空间复杂度O(1)
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
//首先保存两者的头
/*
if(l1==nullptr && l2==nullptr)
return nullptr;
else if(l1==nullptr)
return l2;
else if(l2==nullptr)
return l1; */
ListNode *h1=l1;
int carry=0;
do{
int sum=l1->val+l2->val+carry; //如果传进来的节点是nullptr
l1->val=l2->val=sum%10; //不确定谁是最后的确定链表
carry=sum/10;
if(l1->next!=nullptr && l2->next!=nullptr){
l1=l1->next;
l2=l2->next;
}
else
break;
}while(1); //直到其中一个节点为空了
//无论哪个长都用第一个链表来额return
if(l1->next==nullptr && l2->next==nullptr){
if(carry!=0){
ListNode* t=new ListNode(carry);
l1->next=t;
return h1;
}
return h1;
}
if(l2->next!=nullptr)
l1->next=l2->next;
l1=l1->next;
while(carry!=0 ){
int sum=carry+l1->val;
carry=sum/10;
l1->val=sum%10;
if(l1->next==nullptr && carry!=0){
ListNode* t=new ListNode(carry);
l1->next=t;
break;
}
l1=l1->next;
}
return h1;
}
};
递归方法:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
if (l1 == NULL and l2 == NULL) return NULL;
else if (l1 == NULL) return l2;
else if (l2 == NULL) return l1;
int a = l1->val + l2->val;
ListNode *p = new ListNode(a % 10);
p->next = addTwoNumbers(l1->next,l2->next);
if (a >= 10) p->next = addTwoNumbers(p->next, new ListNode(1));
return p;
}
};
携带进位:
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int carry=0;
ListNode* dummty=new ListNode();
ListNode* head=dummty;
while(l1 || l2 || carry){
int val1=0,val2=0;
if(l1){
val1=l1->val;
l1=l1->next;
}
if(l2){
val2=l2->val;
l2=l2->next;
}
int sum=val1+val2+carry;
carry=sum/10;
sum=sum%10;
ListNode* t=new ListNode(sum);
dummty->next=t;
dummty=t;
}
return head->next;
}
};