LeetCode-Algorithm2 C++的链表

You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)

Output: 7 -> 0 -> 8

这道题如果采用链表来做的话要考验一下细心程度,最后要判断一下是否有carryout,而不能仅以l1和l2是否为空来判断是否可以返回答案了。

还有C++中链表的节点支持构造器,比如:

struct ListNode
{
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};
就可以直接new ListNode(0)来构造一个val=0,next=NULL的新节点了
链表解法:

class Solution
{
	int unit,tempsum;
	bool carryout=false;
	public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
	{
		ListNode *pans=new ListNode(0);
		ListNode *ans = pans;
		if (l1->val + l2->val >= 10)
		{
			carryout = true;
			pans->val = (l1->val + l2->val) % 10;
		}
		else
		{
			pans->val = l1->val + l2->val;
			carryout = false;
		}
		l1 = l1->next;
		l2 = l2->next;
		while (l1 != NULL||l2 != NULL)
		{
			pans->next = new ListNode(0);
			pans = pans->next;
			if (l1 != NULL&&l2 != NULL)
			{
				if (carryout == true)
				{
					pans->val = 1;
				}
				tempsum = pans->val + l1->val + l2->val;
				if (tempsum >= 10)
				{
					pans->val = tempsum % 10;
					carryout = true;
				}
				else
				{
					pans->val = tempsum;
					carryout = false;
				}
				l1 = l1->next;
				l2 = l2->next;
			}
			else if (l1 == NULL&&l2 != NULL)
			{
				if (carryout == true)
				{
					pans->val = 1;
				}
				tempsum = pans->val + l2->val;
				if (tempsum >= 10)
				{
					pans->val = tempsum % 10;
					carryout = true;
				}
				else
				{
					pans->val = tempsum;
					carryout = false;
				}
				l2 = l2->next;
			}
			else if (l1 != NULL&&l2 == NULL)
			{
				if (carryout == true)
				{
					pans->val = 1;
				}
				tempsum = pans->val + l1->val;
				if (tempsum >= 10)
				{
					pans->val = tempsum % 10;
					carryout = true;
				}
				else
				{
					pans->val = tempsum;
					carryout = false;
				}
				l1 = l1->next;
			}
		}
		if (carryout == true)
		{
			pans->next = new ListNode(1);
		}
		return ans;
	}
};
还有突然发现国外的OJ都是给定了接口,只让你实现一个函数,而不是全部代码都由你编写,做了那么多国内的OJ还是有点不习惯。用面向对象的语言写算法也确实没有面向过程那么习惯。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值