CD 114 两个链表生成相加链表

题目描述
假设链表中每一个节点的值都在 0 - 9 之间,那么链表整体就可以代表一个整数。
给定两个这种链表,请生成代表两个整数相加值的结果链表。
例如:链表 1 为 9->3->7,链表 2 为 6->3,最后生成新的结果链表为 1->0->0->0。
输入描述:
第一行两个整数 n 和 m,分别表示两个链表的长度。

第二行 n 个整数 ai 表示第一个链表的节点。

第三行 m 个整数 bi 表示第二个链表的节点。
输出描述:
输出一行整数表示结果链表。
示例1
输入
复制
3 2
9 3 7
6 3
输出
复制
1 0 0 0

思路:先写一个链表反转函数,然后反转两个链表,相加,得到的链表再反转。

 # include <bits/stdc++.h>
using namespace std;

struct list_node{
    int val;
    struct list_node * next;
};
int n, m;

list_node * input_list(int n)
{
    int val;
    list_node * phead = new list_node();
    list_node * cur_pnode = phead;
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &val);
        if (i == 1) {
            cur_pnode->val = val;
            cur_pnode->next = NULL;
        }
        else {
            list_node * new_pnode = new list_node();
            new_pnode->val = val;
            new_pnode->next = NULL;
            cur_pnode->next = new_pnode;
            cur_pnode = new_pnode;
        }
    }
    return phead;
}


list_node * reverse(list_node * head1) 
{
	list_node * pre=NULL,* next=NULL;
    while(head1!=NULL)
	{
		next=head1->next;
		head1->next=pre;
		pre=head1;
		head1=next;
	}
	return pre;
}


list_node * add_list(list_node * head1, list_node * head2)
{
    //在下面完成代码
    head1=reverse(head1);
    head2=reverse(head2);
	list_node * p=  n>m ? head1 : head2; 
    list_node * p1=p;
	n=max(n,m);
    int res=0;
    
    while(n--)
	{
		if( head1!=NULL && head2!=NULL )
		{
			res=res+head1->val+head2->val;
			head1=head1->next;
			head2=head2->next;
			p->val=res%10;
			res/=10;
		}
		else if( head1==NULL && head2!=NULL )
		{
			res=res+head2->val;
			head2=head2->next;
			p->val=res%10;
			res/=10; 
		}
		else
		{
			res=res+head1->val;
			head1=head1->next;
			p->val=res%10;
			res/=10; 
		}
		p= p->next==NULL ? p : p->next ;
	}
    
    
	if(res>0)
	{
		list_node *x=new list_node;
		x->next=NULL;
		x->val=res;
		p->next=x;
	}
    
	return reverse(p1) ; 
}
void print_list(list_node * head)
{
    while (head != NULL) {
        printf("%d ", head->val);
        head = head->next;
    }
    puts("");
}



int main ()
{
    
    scanf("%d%d", &n, &m);
    list_node * head1 = input_list(n), * head2 = input_list(m);
    list_node * new_head = add_list(head1, head2);
    print_list(new_head);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值