题解 | #链表相加(二)#
链表相加(二)
https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b
class Solution {
public:
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
if(head1==NULL||head2==NULL)
return (head1==NULL)? head1:head2;
ListNode* ans = new ListNode(-1);
ListNode* res = ans;
reverselist(head1);
reverselist(head2);
//cout << head1->val << "|" << head2->val << endl;
int flag = 0;
while(head1!=NULL||head2!=NULL||flag==1){
int tem1 = head1==NULL? 0:head1->val;
int tem2 = head2==NULL? 0:head2->val;
//cout << tem1 << "||" << tem2 << endl;
int tem = tem1+tem2+flag;
flag = tem/10;
int anstem = tem%10;
//cout << tem << "|" << anstem << endl;
ans->next = new ListNode(anstem);
ans = ans->next;
//cout << anstem << endl;
if(head1!=NULL)
head1 = head1->next;
if(head2!=NULL)
head2 = head2->next;
}
reverselist(res->next);
return res->next;
}
void reverselist(ListNode* &head){//? 结构体指针只是值传递,不是地址传递 注意加引用
//ListNode* pre; //? 结构体指针变量不能连续定义
ListNode* cur;
ListNode* next;
cur = head->next;
head->next = NULL;
next = cur->next;
while(cur!=NULL){
cur->next = head;
head = cur;
cur = next;
next = next->next;
}
}
};

