Hello all,
I am trying to add two objects of integers.
Object A: 92999
Object B: 22
My add method works when A is being added by B, but not the other way around because the amount of nodes is less. I should know how to add a node but this time I am already at the end of the list, which I thought would be easy. Can anyone see where I am going wrong? Many thanks.
void Number::Add(const Number& Num)
{
digit *temp = head;
int newLength = GetLength();
digit *temp2 = Num.head;
int checkLength = Num.GetLength();
int carry = 0;
int num1;
int num2;
if (IsEmpty() == 1)
{
cout << "One of the list contains no Numbers" << endl;
}
else
{
if (checkLength > newLength)
{
newLength = checkLength;
}
for(int i = 0; i < newLength; i++)
{
if (temp == NULL)
{
num1 = 0;
digit *newPtr = new digit;
newPtr->prev = head;
newPtr->next = temp;
newPtr->Value = carry;
temp = newPtr;
size = size + 1;
}
else
num1 = temp->Value;
if(temp2 == NULL)
num2 = 0;
else
num2 = temp2->Value;
if (num1 + num2 + carry <= 9)
{
temp->Value = num1 + num2 + carry;
temp = temp->next;
if(temp2 != NULL)
temp2 = temp2->next;
carry = 0;
}
else
{
temp->Value = num1 + num2 + carry - 10;
temp = temp->next;
if (temp2 != NULL)
temp2 = temp2->next;
carry = 1;
}
}
if (temp == NULL && carry == 1)
{
temp = head;
temp = temp->next;
newLength = newLength + 1;
digit *newPtr = new digit;
size = newLength;
if (size > 2 )
{
newPtr->Value = carry;
head->next = temp;
newPtr->next = NULL;
if (head == NULL)
head->next = temp;
else
{
while (temp->next !=NULL)
{
temp = temp->next;
}
temp->next = newPtr;
}
newPtr->prev = temp;
}
else
{
newPtr->Value = carry;
newPtr->prev = head;
newPtr->next = temp;
if (head != NULL)
head->next = newPtr;
}
}
}
}