Ch2-4:add reverse 1 digit format number in linked list

来源:互联网 发布:三菱plc编程入门 编辑:程序博客网 时间:2024/04/30 10:04

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

第一个想法是先把linkedlist变为int,相加,再初始化为一个linkedlist,但这样很耗时间:max(O(list1),O(list2))+O(listSUM)=O(listSUM).

第二种就是CC里面给的方法:因为recursive本质就是stack,而stack是LIFO,正好可以反过来,所以就用了这个方法:

node* addlist(node *list1, node * list2, int carry){node* result = new node();int value = carry;if(list1!=NULL)value += list1->data;if(list2!=NULL)value += list2->data;result->data = value % 10;if(list1!=NULL || list2!=NULL || value >= 10){node* more = addlist(list1!=NULL? list1->next: NULL,  list2!=NULL? list2->next: NULL,  value>=10? 1:0);result->next = more;}return result;}

完整代码在这里。但是有个问题!


输出结果是:
Executing the program....$demo 1 2 9 3 end39219 9 2 end2990 2 2 4 0 end  //这里应该输出0 2 2 4 end, 为什么多个0?4220



0 0
原创粉丝点击