两个list相加

来源:互联网 发布:网络图编辑软件 编辑:程序博客网 时间:2024/05/22 02:02

150题 2.5

ListNode* AddList(ListNode* root1, ListNode* root2,int& carry){if (root1==NULL && root2==NULL)return NULL;ListNode* result = AddList(root1->next,root2->next,carry);ListNode* temp = NULL;temp = new ListNode(0);temp->val = (root1->val+root2->val+carry)%10;carry = (root1->val+root2->val+carry)/10;temp->next = result;return temp;}ListNode* PadList(ListNode* root,int length){if (length==0)return root;ListNode* temp = new ListNode(0);temp->next = root;return PadList(temp,length-1);}ListNode* AddList(ListNode* root1, ListNode* root2){if (root1==NULL && root2==NULL)return NULL;if (root1==NULL)return root2;if (root2 == NULL)return root1;int len1=0;ListNode* temp = root1;while(temp!= NULL){len1++;temp = temp->next;}int len2=0;temp = root2;while(temp!= NULL){len2++;temp = temp->next;}int carry = 0;ListNode* result;if (len1<len2){temp=PadList(root1,len2-len1);result=AddList(temp,root2,carry);}else{temp=PadList(root2,len1-len2);result=AddList(root1,temp,carry);}if (carry == 1){ListNode* last= new ListNode(1);last->next = result;result = last;}return result;}

1. 本来的想法是两个数都有的部分用一个函数处理,只有一个数的在用另一个函数处理………………
    把短的数用pad函数全部填上0,这样两个list的长度就一样了

2. 不要忘了,如果最后carry为1,要再多添加一个处理!!

3. new啊,new,又犯了错误,没有new,直接用了dangling指针。 另外new出来的指针返回是没有问题的,和上一篇c++指针测试里面的例子不同。





原创粉丝点击