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;
			}
		}
	}
}

Which end of the list holds the least significant digits?

Adding 12 to 3456 for example, adds 2 and 6 together because they're the same rank at the end of the list.
Not adding 1 and 3 together because they're at the head of the list.

As usual, I post my question and answer my own question right afterwards. I just had to switch, or swap the pointers around so the function would always have the largest amount of nodes. Kinda cool, don't have to waste memory to add more nodes now.

But in my method, it will add 2 to 6 and 1 to 5 and then it would pretty much skip the 34 because the loop was set for the length of 2--- hince the "1" and "2". Now though, it will swap the 3456 to the first set and then add 12 to it.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.