leetcode两数相加,为什么执行的时候输入为0
用的是C写的,编译能通过,但是执行的时候输入一直是0
struct ListNode* create(int data)
{
struct ListNode* head=malloc(sizeof(struct ListNode));
head->val=data;
head->next=NULL;
return head;
}
void insert(struct ListNode* l,int data)
{
struct ListNode* node=create(data);
node->next=l->next;
l->next=node;
}
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode* p1=l1;
struct ListNode* p2=l2;
int temp1[3]={0};
int temp2[3]={0};
int r;
for(int i=2;i>=0;i--)
{
if(p1==NULL||p2==NULL)continue;
temp1[i]=p1->val;
p1=p1->next;
temp2[i]=p2->val;
p2=p2->next;
}
r=temp1[0]+temp1[1]*10+temp1[2]*100+temp2[0]+temp2[1]*10+temp2[2]*100;
struct ListNode *head;
head=create(r%10);
insert(head,(r/100));
insert(head,((r%100)/10));
return head;
}
在这个程序中,输入为0的原因可能是因为输入的两个链表l1和l2是空链表。如果l1和l2都是空链表,那么在循环中不会执行任何操作,因此temp1和temp2数组的所有元素都不会被赋值。在这种情况下,r的初始值为0,因此输出也是0。
另外,如果输入的两个链表中的节点数量少于3个,那么temp1和temp2数组中的某些元素也可能是0,从而导致r的初始值为0。
为了解决这个问题,可以在循环中使用计数器来统计输入链表中的节点数量,确保在循环中只处理输入链表中实际存在的节点。同时,在计算r的值时,也需要考虑输入链表中节点数量不足3个的情况。可以修改addTwoNumbers函数
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){
struct ListNode *p1=l1, *p2=l2;
int temp1[3]={0}, temp2[3]={0};
int r=0, count=0;
while (p1!=NULL || p2!=NULL || count<3) {
if (p1!=NULL) {
temp1[count] = p1->val;
p1 = p1->next;
}
if (p2!=NULL) {
temp2[count] = p2->val;
p2 = p2->next;
}
count++;
}
r = temp1[0] + temp1[1]*10 + temp1[2]*100 + temp2[0] + temp2[1]*10 + temp2[2]*100;
struct ListNode *head = create(r%10);
insert(head, r/100);
if (count >= 2) insert(head, (r%100)/10);
return head;
}
在修改后的addTwoNumbers函数中,添加了一个计数器count来统计输入链表中的节点数量。在循环中,只有当count小于3并且输入链表中还有节点未处理时,才会继续处理下一个节点。此外,在计算r的值时,也需要考虑输入链表中节点数量不足3个的情况。如果输入链表中节点数量不足3个,那么在insert函数中也只需要插入相应数量的节点即可。