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

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

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

// 2-4 tony

#include 
   
   
    
    

using namespace std;

struct node{
    int data;
    node* next;
};

node* init(int* a, int n){
    node *head, *p;
	for (int i=0; i
    
    
     
     data = a[i];
		if(i==0){
			head = p = nd;
			continue;
		}
		p->next = nd;
		p = nd;
	}
    return head;
}

void print(node* head){
    if(head==NULL) {
        cout << "end" << endl;
        return;  // nust add return here so 
        			// as to jump out of recursion
    }
    cout<
     
     
      
      data<<" ";
    head=head->next;    
	print(head);
}

int linkedlist2int(node* head){
	int value = 0;
	if(head->next!=NULL){
		value = 10 * linkedlist2int(head->next);
	}
	return value+ head->data;
}

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

int main(){
	int n = 3;
	int a[] = {
        //3, 0, 8
        1, 2, 9, 3
    };
    
    int b[] = {
        //4,9,2
        9,9,2
    };

    node* heada = init(a,4);
    print(heada);
    cout << linkedlist2int(heada)<
      
      
     
     
    
    
   
   

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



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值