leetcode:2. 两数相加(链表,中等)

it2023-08-07  67

题目:

分析:链表中有一个经典的错误,自己又犯错了。

代码:

/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode() : val(0), next(nullptr) {} * ListNode(int x) : val(x), next(nullptr) {} * ListNode(int x, ListNode *next) : val(x), next(next) {} * }; */ class Solution { public: ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) { if(l1->val==0&&l1->next==NULL) return l2; if(l2->val==0&&l2->next==NULL) return l1; l1->val=l1->val+l2->val; int c=0;//进位 if(l1->val<10) { c=0; } else{ l1->val=l1->val%10; c=1; } ListNode* ll=l1; while(l1->next&&l2->next) { l1->next->val=l1->next->val+l2->next->val+c; if(l1->next->val<10) { c=0; } else{ l1->next->val=l1->next->val%10; c=1; } l1=l1->next; l2=l2->next; } if(l1->next) {//l1 不空 l2 空 while(l1->next) { l1->next->val=l1->next->val+c; if(l1->next->val<10) { c=0; } else{ l1->next->val=l1->next->val%10; c=1; } l1=l1->next; } } else{ l1->next=l2->next; while(l1->next) { l1->next->val=l1->next->val+c; if(l1->next->val<10) { c=0; } else{ l1->next->val=l1->next->val%10; c=1; } l1=l1->next; } } if(c==1) { l1=ll; while(l1->next) l1=l1->next; l1->next=new ListNode(1); } return ll; } };
最新回复(0)