解题思路:
从链表中取出每一位整型数字,构造成整型整数,相加之后再分别取出每一位构造链表。
#include <stdio.h>
#include <malloc.h>
struct ListNode {
int val;//保存数字
struct ListNode *next;//指针,指向下一个节点
};//链表节点
struct ListNode* create_list(int sum)
{
struct ListNode *l = (struct ListNode*)malloc(sizeof(struct ListNode));
l->next = NULL;
struct ListNode *p;
p = l;
while(sum){
struct ListNode *q = (struct ListNode*)malloc(sizeof(struct ListNode));
q->val = sum % 10;
q->next = l;
sum /= 10;
p->next = q;
p = q;
}
p->next = NULL;
return l;
}//根据形参传进的整数值构造一个逆序链表
void put_list(struct ListNode *l)
{
struct ListNode *p;
p = l->next;
while(p != NULL){
printf("%d -> ", p->val);
p = p->next;
}
printf("NULL");
putchar('\n');
}//输出链表中的每一个元素
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
int i=1; //用来计算从链表取出的数的大小
int sum1 = 0;
int sum2 = 0;
int sum = 0;
struct ListNode *p,*q;
p = l1->next;
q = l2->next;
while(p != NULL){
sum1 += (p->val) * i;
i *= 10;
p = p->next;
}
i=1;
while(q != NULL){
sum2 += (q->val) * i;
i *= 10;
q = q->next;
}
sum = sum1 + sum2;
return create_list(sum);
}//两链表相加函数
int main(void)
{
int num1,num2;
struct ListNode *p1,*p2,*p3;
puts("enter the two elemts of the two list: ");
scanf("%d%d", &num1,&num2);
p1 = create_list(num1);
p2 = create_list(num2);
put_list(p1);
put_list(p2);
p3 = addTwoNumbers(p1,p2);
put_list(p3);
return 0;
}
运行结果如下图