鏈表表示的數字相加

題目

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

譯文:

你有兩個由單鏈表表示的數。每個結點代表其中的一位數字。數字的存儲是逆序的, 也就是說個位位於鏈表的表頭。寫一函數使這兩個數相加並返回結果,結果也由鏈表表示。

例子:(3 –> 1 –> 5), (5 –> 9 –> 2)

輸入:8 –> 0 –> 8

思路:

時間上思路與合併兩個有序單鏈表一樣,

從低位開始,逐位開始相加,

/*
考慮情況比較多,
1.有空鏈表
2.兩個鏈表長度不一樣
3.有進位
*/
linKNode* addList(LinkNode * listOne, LinkNode * listTwo)
{
	int num;
	LinkNode * newList;  //結果放在新鏈表中
	newList=NULL;
	LinkNode *temP;
	int flag=0;
	if(NULL==listOne,NULL==listTwo)
	{
		return NULL;
	}
	while(listOne!=NULL&&listTwo!=NULL)//依位相加
	{
			num=listOne->a+listTwo->a+flag;
		flag=num/10;
		num=num%10;
		if(NULL==newList)
		{
			newList=new LinkNode();
			newList->a=num;
			temP=newList;
		}
		else
		{
			temP->next=new LinkNode();
			temP->next->a=num;
			temP=temP->next;
		}
		listOne=listOne->next;
		listTwo=listTwo->next;
		
	}

	while(listOne!=NULL)  //鏈表長度不一致,listOne
	{
		temP->next=new LinkNode();
		temP=temP->next;
		num=listOne->a+flag;
		flag=num/10;
		num=num%10;
		temP->a=num;
		listOne=listOne->next;
	}

	while(listTwo!=NULL)
	{
		temP->next=new LinkNode();
		temP=temP->next;
		num=listTwo->a+flag;
		flag=num/10;
		num=num%10;
		temP->a=num;
		listTwo=listTwo->next;
	}
	if(flag>0)  //最後位有進位
	{
		temP->next=new LinkNode();
		temP=temP->next;
		temP->a=flag;

	}
	temP->next=NULL;
	cout<<"result :"<<endl;
	
	return newList;

}


發佈了27 篇原創文章 · 獲贊 5 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章