Add two numbers represented by linked lists

#include <iostream>
#include <string>

struct node
{
	int data;
	node* next;
};


void push(node** head_ref, int new_data)
{
	node* new_node = new node();
	new_node->data = new_data;
	new_node->next = *head_ref;
	*head_ref = new_node;
};

int getSize(node* n)
{
	int size = 0;
	while(n)
	{
		n = n->next;
		size++;
	}

	return size;
};

node* addSameSize(node* l1, node* l2, int* carry)
{
	if (l1 == NULL)
		return NULL;

	int sum;
	node* result = new node();
	result->next = addSameSize(l1->next, l2->next, carry);
	sum = l1->data + l2->data + *carry;
	*carry = sum / 10;
	result->data = sum % 10;

	return result;

};

void swapPointer(node** n1, node** n2)
{
	node* t = *n1;
	*n1 = *n2;
	*n2 = t;
};

void addCarryToRemaining(node* l1, node* cur, int* carry, node** result)
{
	int sum;
	if (l1 != cur)
	{
		addCarryToRemaining(l1->next, cur, carry, result);

		sum = l1->data + *carry;
		*carry = sum / 10;
		sum %= 10;
		push(result, sum);
	}
};


void addList(node* l1, node* l2, node** result) // result should be passed as pointer to pointer
{

	if (l1 == NULL)
	{
		*result = l2;
		return;
	}
	if (l2 == NULL)
	{
		*result = l1;
		return;
	}

	int size1 = getSize(l1);
	int size2 = getSize(l2);

	int carry = 0;

	if (size1 == size2)
		*result = addSameSize(l1, l2, &carry);
	else
	{
		int diff = std::abs(size1 - size2);
		if (size1 < size2)
			swapPointer(&l1, &l2);
		node* cur;
		for (cur = l1; diff--; cur = cur->next);

		*result = addSameSize(cur, l2, &carry);

		// add carry to remaining
		addCarryToRemaining(l1, cur, &carry, result);


		if (carry)
			push(result, carry);
	}
};


void printList(node* n)
{
	while (n)
	{
		std::cout << n->data << " ";
		n = n->next;
	}
	std::cout << "\n";
	return;
};

int main()
{
	int l1[] = {9, 9, 9};
	int l2[] = {1, 8};

	int size1 = sizeof(l1) / sizeof(l1[0]);
	int size2 = sizeof(l2) / sizeof(l2[0]);

	node* head1 = NULL, *head2 = NULL, *result = NULL;

	int i;
	for (int i = size1 - 1; i >= 0; --i)
		push(&head1, l1[i]);
	for (int i = size2 - 1; i >= 0; --i)
		push(&head2, l2[i]);
	
	addList(head1, head2, &result);
	printList(result);

	return 0;
}

你可能感兴趣的:(Add two numbers represented by linked lists)