You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.
EXAMPLE
Input: (3 -> 1 -> 5), (5 -> 9 -> 2)
Output: 8 -> 0 -> 8
第一个想法是先把linkedlist变为int,相加,再初始化为一个linkedlist,但这样很耗时间:max(O(list1),O(list2))+O(listSUM)=O(listSUM).
第二种就是CC里面给的方法:因为recursive本质就是stack,而stack是LIFO,正好可以反过来,所以就用了这个方法:
node* addlist(node *list1, node * list2, int carry){
node* result = new node();
int value = carry;
if(list1!=NULL)
value += list1->data;
if(list2!=NULL)
value += list2->data;
result->data = value % 10;
if(list1!=NULL || list2!=NULL || value >= 10){
node* more = addlist(list1!=NULL? list1->next: NULL,
list2!=NULL? list2->next: NULL,
value>=10? 1:0);
result->next = more;
}
return result;
}
完整代码在这里。但是有个问题!
// 2-4 tony
#include
using namespace std;
struct node{
int data;
node* next;
};
node* init(int* a, int n){
node *head, *p;
for (int i=0; idata = a[i];
if(i==0){
head = p = nd;
continue;
}
p->next = nd;
p = nd;
}
return head;
}
void print(node* head){
if(head==NULL) {
cout << "end" << endl;
return; // nust add return here so
// as to jump out of recursion
}
cout<data<<" ";
head=head->next;
print(head);
}
int linkedlist2int(node* head){
int value = 0;
if(head->next!=NULL){
value = 10 * linkedlist2int(head->next);
}
return value+ head->data;
}
node* addlist(node *list1, node *list2, int carry){
node* result = new node();
int value = carry;
if(list1!=NULL)
value += list1->data;
if(list2!=NULL)
value += list2->data;
result->data = value % 10;
if(list1!=NULL || list2!=NULL || value >= 10){
node* more = addlist(list1!=NULL? list1->next: NULL,
list2!=NULL? list2->next: NULL,
value>=10? 1:0);
result->next = more;
}
return result;
}
int main(){
int n = 3;
int a[] = {
//3, 0, 8
1, 2, 9, 3
};
int b[] = {
//4,9,2
9,9,2
};
node* heada = init(a,4);
print(heada);
cout << linkedlist2int(heada)<
输出结果是:
Executing the program....
$demo
1 2 9 3 end
3921
9 9 2 end
299
0 2 2 4 0 end //这里应该输出0 2 2 4 end, 为什么多个0?
4220