Add Two Numbers

本文介绍了一种使用 C++ 实现的 AddTwoNumbers 算法,该算法能够处理两个链表表示的大数相加的问题。通过递归方式创建链表,并实现了相加操作,最后打印出结果链表。

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

Add Two Numbers算法题,c++实现:

#include<iostream>
using namespace std;

class Solution
{
	public:
		ListNode * addTwoNumbers(ListNode * l1, ListNode * l2);
};

ListNode * Solution::addTwoNumbers(ListNode * l1, ListNode * l2)
{
	ListNode * root = new ListNode(1);
	if(root == NULL)
	{
		cout << "Memory Location Error ! " << endl;
		return NULL;
	}
	else
	{
		ListNode * p1 = l1;
		ListNode * p2 = l2;
		ListNode * p_cur = root;
		int jinwei = 0;
		while(p1 != NULL && p2 != NULL)
		{
			int value = p1->val + p2->val + jinwei;
			ListNode * p = new ListNode(value % 10);
			jinwei = value / 10;
			p->next = NULL;
			p_cur->next = p;
			p_cur = p;
			p1 = p1->next;
			p2 = p2->next;
		}
		if(p1 == NULL && p2 != NULL)
		{
			while(p2 != NULL)
			{
				int value = p2->val + jinwei;
				ListNode * p = new ListNode(value % 10);
				jinwei = value / 10;
				p_cur->next = p;
				p_cur = p;
				p2 = p2->next;
			}
			if(jinwei != 0)
			{
				ListNode * p = new ListNode(jinwei);
				p_cur->next = p;
			}
		}
		else if(p2 == NULL && p1 != NULL)
		{
			while(p1 != NULL)
			{
				int value = p1->val + jinwei;
				ListNode * p = new ListNode(value % 10);
				jinwei = value / 10;
				p_cur->next = p;
				p_cur = p;
				p1 = p1->next;
			}
			if(jinwei != 0)
			{
				ListNode * p = new ListNode(jinwei);
				p_cur->next = p;
			}
		}
		else if(p1 == NULL && p2 == NULL)
		{
			if(jinwei != 0)
			{
				ListNode * p = new ListNode(jinwei);
				p_cur->next = p;
			}
		}
	}
	return root->next;
}
ListNode * CreateList(int size)
{
	if(size == 0)
		return NULL;
	else
	{
		cout << "please enter the value : " << endl;
		int value;
		cin >> value;
		ListNode * p = new ListNode(value);
		if(p == NULL)
		{
			cout << "Memory Location Error ! " << endl;
			return NULL;
		}
		else
		{
			p->next = CreateList(size - 1);
			return p;
		}
	}
}

void ListPrint(ListNode * l)
{
	ListNode * p = l;
	while(p != NULL)
	{
		cout << p->val << endl;
		p = p->next;
	}
	return;
}

int main(int argc, char ** argv)
{
	cout << "please enter the number of nodes in list1 : " << endl;
	int size1;
	cin >> size1;
	ListNode * l1 = CreateList(size1);
	//ListPrint(l1);
	cout << "please enter the number of nodes in list2 : " << endl;
	int size2;
	cin >> size2;
	ListNode * l2 = CreateList(size2);
	Solution solution = Solution();
	ListNode * result = solution.addTwoNumbers(l1, l2);
	ListPrint(result);
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值