链表表示的数字相加

来源:互联网 发布:政务数据共享平台 杭州 编辑:程序博客网 时间:2024/05/17 19:21

题目

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


原创粉丝点击