如输入 6->3->5->8 ,5->1->4->3
输出1->1-> 5-> 0-> 1
#include <iostream>
using namespace std;
struct Node{
int val;
Node *next;
Node(){
next = NULL;
}
};
void print(Node* root){
while(root!=NULL){
std::cout<<root->val<<" ";
root=root->next;
}
}
Node* reverse(Node *root){
if (!root || !root->next){
return root;
}else{
Node *next = reverse(root->next);
Node *p = next;
while(p && p->next){
p = p->next;
}
p->next = root;
root->next = NULL;
return next;
}
}
Node *add(Node *a,Node* b,int n,int m){
if (n<m){
return add(b,a,m,n);
}
a = reverse(a);
b = reverse(b);
int advance = 0;
Node *add_a = a;
Node *add_b = b;
while(add_a!=NULL && add_b!=NULL){
int va = add_a->val;
int vb = add_b->val;
add_a->val = (va+vb+ advance)%10;
advance = (va+vb + advance)/10;
add_a = add_a->next;
add_b = add_b->next;
}
a = reverse(a);
if(advance){
Node *head = (Node *)malloc(sizeof(Node));
head->next = a;
head->val = 1;
return head;
}else{
return a;
}
}
Node *construct(int A[],int n){
Node * root = NULL;
Node * cur = NULL;
for(int i=0;i<n;i++){
Node* p = (Node*)malloc(sizeof(Node));
p->next=NULL;
p->val = A[i];
if (root==NULL){
root = p;
cur = p;
}else{
cur->next = p;
cur = p;
}
}
return root;
}
int main() {
int inputA[] = {6,3,5,8};
int inputB[] = {5,1,4,3};
Node * a = construct(inputA,4);
Node * b = construct(inputB,4);
Node * res = add(a,b,4,3);
print(res);
cout << "Hello World!" << endl;
}