行业知识
力扣崩溃题:链表相加
2026-11-17 13:42:14
来源:互联网转载
struct ListNode* addTwoNumbers(struct ListNode* l1, struct ListNode* l2){ int sum=0, carry = 0; struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode)); struct ListNode* p = head; while(l1 || l2 || carry) { sum = 0; if(l1) { sum += l1->val; l1 = l1->next; } if(l2) { sum += l2->val; l2 = l2->next; } sum += carry; struct ListNode* newNode = (struct ListNode*)malloc(sizeof(struct ListNode)); newNode->val = sum >=10 ? sum%10 : sum; newNode->next = NULL; carry = sum >=10 ? 1 : 0; p->next = newNode; p = p->next; } return head->next;} index.php/tags-41973.html" >���于力扣的用例太大了,导致笔者的方法用不了,就是下面的,力扣你无敌了
/** * Definition for singly-linked list. * struct ListNode { * int val; * struct ListNode *next; * }; */struct ListNode* addTwoNumbers(struct ListNode* head1, struct ListNode* head2){ if(head1->val+head2->valnext==NULL&&head2->next==NULL) { head1->val=head1->val+head2->val; return head1; } if(head1->val+head2->val==10&&head1->next==NULL&&head2->next==NULL) { head1->val=0; struct ListNode*point3=(struct ListNode*)malloc(sizeof(struct ListNode)); point3->next=NULL; point3->val=1; head1->next=point3; return head1; }long long count1=0;long long count2=0;long long arr1[1000];long long arr2[1000];int i=0;int j=0;struct ListNode*point1=head1;struct ListNode*point2=head2;while(point1){ arr1[i]=point1->val; i++; point1=point1->next;}while(point2){ arr2[j]=point2->val; j++; point2=point2->next;}long good=1;long bad=1;for(int x=0;xnext=NULL;struct ListNode*point4=head1;for(int x=1;xnext=NULL; point3->val=arr5[x]; point4->next=point3; point4=point4->next;}return head1;}