Addition and Multiplication of Huge Numbers Using Doubly Linked List - C ++
Addition and Multiplication of Huge Numbers Using Doubly Linked List - C ++
h>
#include<string>
#include<iostream>
class node
{
public:
int data;
node *prev;
node *next;
node( int data)
{
this->data = data;
this->next = NULL;
this->prev = NULL;
}
};
class hugeint
{
public:
node* front;
node* rear;
int size;
hugeint()
{
front = rear = NULL;
size=0;
}
void insertend(node*);
void insertfront(node*);
void initialise(string);
//void mult(hugeint*, hugeint*);
void display();
};
int val,a1,b1;
while(p!=a.front->prev || q!=b.front->prev)
{
if(p==a.front->prev)
{ a1 = 0;
}
else
{
a1 = p->data;
}
if(q == b.front->prev)
{
b1=0;
}
else
{
b1 = q->data;
}
val = a1+b1+carry;
node* n = new node(val%10);
c.insertfront(n);
if(val/10)
{
carry = val/10;
}
else
{
carry = 0;
}
if(p!=NULL) p=p->prev;
if(q!=NULL) q=q->prev;
}
if(carry)
{
node * n = new node(carry);
c.insertfront(n);
}
return c;
}
while(q!=b.front->prev)
{
p = a.rear;
r = d.rear;
for(int i = 0; i<shift ; i++)
{
r=r->prev;
}
while(p!=a.front->prev)
{
val = (q->data * p->data)+carry;
val = r->data+val;
r->data = val%10;
carry = (val/10);
r = r->prev;
p = p->prev;
}
while(carry)
{
val = r->data+carry;
r->data=val%10;
carry = val/10;
r = r->prev;
}
q=q->prev;
shift++;
}
/*r = d.front;
while(r->data==0)
{
node * temp = r;
r=r->next;
delete(temp);
}
d.front =r; */
return d;
void hugeint::insertend(node* n)
{
if(front == NULL)
{
front = rear = n;
}
else
{
n->prev = rear;
rear->next = n;
rear = n;
}
size++;
}
void hugeint::insertfront(node*n)
{
if(front == NULL)
{ front=rear=n;
}
else
{
n->next = front;
front->prev=n;
front = n;
}
size++;
}
void hugeint::initialise(string s)
{
int l = s.length();
for(int i =0;i<s.length();i++)
{
node *n = new node(s[i]-'0');
insertend(n);
void hugeint::display()
{
if(front==NULL)
{
cout<<"\nEmpty";
return;
}
else
{
node* temp = front;
while(temp!=rear)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<temp->data<<endl;
}
}
int main()
{
hugeint a,b,c,d;
string m,n;
c=add(a,b);
cout<<"Result = ";
c.display();
d = mult(a,b);
cout<<"Product = ";
d.display();
}