leetcode之AddTwoNumbers

题设给出两个链表,每个链表皆为逆序的整数,每一个结点代表一位数,

例:2 -> 4 -> 3 + 5 -> 6 -> 4

此要求是

将这两链表相加并输出,格式为7->0->8

此前有一错误思路:

将两链表中的数据读入到一int变量中,然后将这两个int相加,再将这变量的每一位存到新链表的结点中

后发现给出的数据越来越大,超出其容量范围,故此方法不行。

通过的思路是:

将给出的两链表的结点相加,如果小于10就直接赋给p->val,若大于10,就将其结果对10取余的结果赋给p->val,然后将

temp2的值赋为1加到下一次开辟的结点上。

以下为算法:

struct ListNode* addTwoNumbers(struct ListNode* l1,struct ListNode* l2)
{
int x,y,temp,temp2=0,sum=0;
struct ListNode* p1,*p2,*L,*n1,*head;
p1 = l1;
p2 = l2;
L = (struct ListNode*)malloc(sizeof(struct ListNode));
L -> next = NULL;
head = L;
while(p1||p2||temp2)
{
n1  = (struct ListNode*)malloc(sizeof(struct ListNode));
if(!p1)
{
x = 0;
}
if(!p2)
{
y = 0;
}
if(p1)
x = p1 -> val;
if(p2)
y = p2 -> val;
temp = x + y;
sum = temp + temp2;
printf("x= %d,y= %d,temp= %d,temp2= %d\n",x,y,temp,temp2);
if(temp + temp2 <10&&temp2==0)
{
n1->val=temp;
}
if(temp + temp2 < 10&&temp2==1)
{
printf("this is one\n");
n1 -> val = temp+temp2;
temp2=0;
}
else if(temp + temp2 >10)
{
printf("this is two\n");
temp2 = (sum)/10;
temp = (sum)%10;
n1 -> val = temp;
}
if(temp > 9)
{
printf("this is three\n");
temp2 = temp/10;
temp = temp%10;
n1 -> val = temp;
// n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
// n2 -> val = temp2;
}
printf("sum: %d\n",n1->val);
if(n1->val < 0 || n1 -> val >9)
{
n1 -> val =0;
}
n1 -> next = NULL;
L -> next = n1;
L = n1;
if(p1)
{
p1 = p1 -> next;
}
if(p2)
{
p2 = p2 -> next;
}
}
return head->next;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值