两个链表相加

You have two numbers represented by a linked list, where each node contains a single digit. The digits are stored in reverse order, such that the 1’s digit is at the head of the list. Write a function that adds the two numbers and returns the sum as a linked list.

EXAMPLE

Input: (3 -> 1 -> 5), (5 -> 9 -> 2)

Output: 8 -> 0 -> 8,


下面是我回来之后写的程序。

#include<iostream>
using namespace std;

//节点的定义
struct Node
{
	int val;
	struct Node *next;
	Node(int v):val(v),next(NULL){}
};

//新建一个链表
Node* createList()
{
	int n;
	Node *head=NULL;
	Node *tail=NULL;
	while(cin>>n&&n!=-1)
	{
		if(!head)
		{
			head=new Node(n);
			tail=head;
		}
		else
		{
			tail->next=new Node(n);
			tail=tail->next;
		}
	}
	return head;
}

//计算两数相加
class Plus
{
public:
	static Node* plus(Node* n1, Node* n2)
	{
		if(!n1)					//不能为空,否则立即返回
			return n2;
		if(!n2)
			return n1;			//不能为空,否则立即返回

		int midNum=0;           //进位数
		Node* returnList = NULL;    //要返回的链表
		Node* tail = NULL;			//尾节点

		while(n1&&n2)		//两链表都不为空的时候
		{
			if(!returnList)   //头节点为空的时候
			{
				returnList = new Node(n1->val+n2->val+midNum);
				tail=returnList;
			}
			else
			{
				tail->next = new Node(n1->val+n2->val+midNum);
				tail = tail->next;
			}
			if(tail->val>=10)
			{
				tail->val-=10;
				midNum=1;
			}
			else
			{
				midNum=0;
			}
			n1=n1->next;
			n2=n2->next;
		}
		if(!n1&&!n2&&midNum==1)   //两个链表已经相加完,但是仍然有进位
		{
			tail->next = new Node(1);
			midNum=0;
		}
		while(n1)
		{
			tail->next = new Node(n1->val+midNum);
			tail=tail->next;
			if(tail->val>=10)
			{
				tail->val-=10;
				midNum=1;
			}
			else
			{
				midNum=0;
			}
			n1=n1->next;
		}
		while(n2)
		{
			tail->next = new Node(n2->val+midNum);
			tail=tail->next;
			if(tail->val>=10)
			{
				tail->val-=10;
				midNum=1;
			}
			else
			{
				midNum=0;
			}
			n2=n2->next;
		}
		if(midNum==1)
		{
			tail->next = new Node(1);
		}
		return returnList;
	}
};

//主方法,用作测试
int main()
{
	Node* n1 = createList();
	Node* n2 = createList();
	Node* returnData = Plus::plus(n1,n2);
	while(returnData)
	{
		cout<<returnData->val;
		if(returnData->next!=NULL)
			cout<<"->";
		returnData=returnData->next;
	}
	cout<<endl;
	return 0;
}

如此简单的题目,我居然不能立刻做出来,真是惭愧。于是,深夜将它弄出来。其实还有另外一种更好的算法,下次有空补上。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值