W:
将需要的两个链表进行反转,便于计算;
叠加后的链表为符合题目要求,需要再次反转
N:
ListNode* cur= new ListNode(val);方式增加新的节点
注意遍历时需要判断是否为空,到下一个也需要判断
如果两个链表都为空,但是还有进位,则需要继续循环
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode *reverseList(ListNode *head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode *l = head, *r = l->next;
l->next = nullptr;
while (r) {
ListNode *t = r->next;
r->next = l;
l = r;
r = t;
}
return l;
}
ListNode* addInList(ListNode* head1, ListNode* head2) {
// write code here
if(head1==nullptr){
return head2;
}
if(head2==nullptr){
return head1;
}
ListNode* l1= reverseList(head1);
ListNode* l2= reverseList(head2);
ListNode* res= new ListNode(0);
ListNode* cur=res;
int l=0;
while(l1 || l2 || l ){
//如果两个链表都为空,但是还有进位,则需要继续循环
int v1= l1? l1->val: 0;//需要判断是否为空节点
int v2=l2 ? l2->val: 0;
int sum=(l+v1+v2)%10;
l=(l+v1+v2)/10;
cur->next=new ListNode(sum);//避免多出节点
cur=cur->next;//note
if(l1) l1=l1->next;//还是需要判断
if(l2) l2=l2->next;
}
res=res->next;
res=reverseList(res);
return res;
}
};

京公网安备 11010502036488号