Add two numbers represented by linked lists

本文介绍了一种使用C++实现链表加法的方法,包括节点创建、链表大小获取、相同长度链表相加、不同长度链表补位相加以及进位处理等关键步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值