需要考虑到如下问题:
(1)由链表存储的数怎么转化为可以进行运算的数值
(2)数值的存储采用哪种数据类型,考虑运算过程中数值可能会超过定义的数据类型值的范围,采用数组形式存储解决溢出问题
(3)数组形式的数值怎么进行加法运算
(4)数值结果如何转化为可用链表存储的形式
#include <stdio.h>
#include <math.h>
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2) {
struct ListNode *L,*p,*q,*r;
int num1[200]={0},num2[200]={0};
L = (struct ListNode *)malloc(sizeof(struct ListNode));
L->next = NULL;
p = l1;
q = l2;
int i = 0;
while (p !=NULL){
num1[i]=p->val;
//printf("%d",num1[i]);
p = p->next;
i+=1;
}
//printf("\n");
int j = 0;
while (q!=NULL){
num2[j]=q->val;
//printf("%d",num2[j]);
q = q->next;
j+=1;
}
printf("\n");
int max = i>j?i:j,k=0;
for(k=0;k<max;k++){
num1[k] = num1[k]+num2[k];
if (num1[k]>9){
num1[k]=num1[k]-10;
num1[k+1]++;
}
//printf("%d",num1[k]);
}
//printf("\n");
int s;
for(s=max;num1[s]==0&&s>0;s--);
for(int t=s;t>=0;t--){
r = (struct ListNode *)malloc(sizeof(struct ListNode));
r->val = num1[t];
r->next = L->next;
L->next = r;
}
return r;
}