1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
|
#include <iostream>
#include <string>
using namespace std;
class Node
{
public:
int val;
Node * next;
Node(){val=0;next=NULL;}
Node(int v){val=v;next=NULL;}
};
Node Plus(Node* a, Node* b, Node* c)
{
if(!a && !b) return 0;
if(!a) return c->val=b->val;
if(!b) return c->val=a->val;
if(a->val + b->val >=10)
{
return c->val= a->val+b->val-10;
a->next->val+1;
}
Plus(a->next, b->next, c->next);
}
Node Minus(Node* a, Node* b, Node* c)
{
if(!a && !b) return 0;
if(!a) return c->val=b->val;
if(!b)return c->val=a->val;
if(a->val-b->val<0)
{
a->val=a->val+10;
c->val = a->val-b->val;
a->next->val-1;
}
else {
c->val = b->val-a->val;
}
Minus(a->next,b->next, c->next);
}
void Print(Node *h)
{
while(h)
{
cout<<h->val;
h=h->next;
}
}
void AddHead(Node*& h, int v)
{
Node *a = new Node(v);
a->next = h;
h=a;
}
int Length(Node *h)
{
int i=0;
while(h)
{
i++;
h=h->next;
}
return i;
}
void DeleteHead(Node*&h)
{
if(!h) return;
Node *t = h;
h=h->next;
delete t;
}
int main()
{
Node* answer = NULL;
string num1="", num2="";
char ansdo, ansop;
do{
cout<<"Enter the first number:";
cin>>num1;
const char *in = num1.c_str();
int i=0;
Node * head1 = NULL;
while(in[i]!='\0')
{
int value = in[i]-'0';
AddHead(head1, value);
i++;
}
cout<<"Enter the second number:";
cin>>num2;
const char *in2 = num2.c_str();
int j=0;
Node * head2 = NULL;
while(in[j]!='\0')
{
int value = in[j]-'0';
AddHead(head2, value);
i++;
}
cout<<"Enter + to add or - to subtract: ";
cin>>ansop;
if ( ansop == '+')
{
answer = Plus(head1,head2,answer);
Print(answer);
}
else if (ansop == '-')
{
if (Length(head1)>Length(head2))
{
head1->val-head2->val;
Print(answer);
}
else
{
Node* tmp=head1;
head1=head2;
head2=tmp;
Minus(head1,head2, answer);
}
}
else cout<<"Wrong Input!"<<endl;
cout<<"Would you like to repeat the calculation? <Y to repeat>:";
cin>>ansdo;
} while(ansdo == 'y' && ansdo == 'Y');
return 0;
}
|