careercup2.4

careercup2.4

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是第一个数的各位,5是第二个数的各位,两个数十位上分别是1,9,百位上分别是5.2

输出是和。和的个位为8,十位为0,百位为8



#include<iostream>
using namespace std;

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

node * add(node *first,node *second){
	node *head=new node();
	//list1保存第一个链表的位置
	//list2保存第二个链表的位置
	//变量i用来保存进位
	//当前位的数据为两个链表上对应位置的数据之和-
	//加上进位之后mod 10(%10)而得
	
	node *list1=first;
	node *list2=second;
	int i=0;

	if(list1==NULL&&list2==NULL)
		return NULL;
	if(list1!=NULL&&list2!=NULL){
		head->data=(list1->data+list2->data+i)%10;
		i=(list1->data+list2->data+i)/10;
		list1=list1->next;
		list2=list2->next;
		
	}	
	else{
		if(list1==NULL)
			return list2;
		else
			return list1;
	}
	node *cur=head;
	while(list1!=NULL&&list2!=NULL){
		node *temp=new node();
		temp->data=(list1->data+list2->data+i)%10;
		i=(list1->data+list2->data+i)/10;
		cur->next=temp;
		cur=cur->next;
		list1=list1->next;
		list2=list2->next;
	}
	while(list1!=NULL){
		node *temp=new node();
		temp->data=(list1->data+i)%10;
		i=(list1->data+i)/10;
		cur->next=temp;
		cur=cur->next;
		list1=list1->next;

	}
	while(list2!=NULL){
		node *temp=new node();
		temp->data=(list2->data+i)%10;
		i=(list2->data+i)/10;
		cur->next=temp;
		cur=cur->next;
		list2=list2->next;

	}
	return head;

}


int main(){
	node *n1=new node();  
    n1->data=5; 
    node *n2=new node();  
    n2->data=7; 
    node *n3=new node();  
    n3->data=5;  
    node *n4=new node();  
    n4->data=6;  
    node *n5=new node();  
    n5->data=8;  
	node *n6=new node();  
    n6->data=2;  
    n1->next=n2;  
    n2->next=n3;  
    n3->next=NULL;  
    n4->next=n5;  
    n5->next=n6;  
	n6->next=NULL;
	node *res=add(n1,n4);
	while(res!=NULL){
		cout<<res->data<<" "<<endl;
		res=res->next;
	}
	//just for test
	system("pause");

	


}


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值