/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
#include <stdio.h>
struct ListNode* reverse(struct ListNode* head)
{
struct ListNode* pre,*cur,*nex;
pre=NULL;
cur=head;
while(cur)
{
nex=cur->next;
cur->next=pre;
pre=cur;
cur=nex;
}
return pre;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
// write code here
//翻转
if(head1==NULL) return head2;
if(head2==NULL) return head1;
struct ListNode* pre1=reverse(head1);
struct ListNode* pre2=reverse(head2);
struct ListNode* H=(struct ListNode* )malloc(sizeof(struct ListNode* ));
struct ListNode* pi=H;
int value;
int flag=0;
//求和
while(pre1 && pre2)
{
struct ListNode* node=(struct ListNode* )malloc(sizeof(struct ListNode* ));
value=pre1->val+pre2->val;
node->val=value;
pi->next=node;
pi=pi->next;
pre1=pre1->next;
pre2=pre2->next;
}
pi->next=pre1==NULL?pre2:pre1;
struct ListNode* pre=H;
struct ListNode* cur=pre->next;
//取值+进位
while(cur)
{
value=cur->val;
cur->val=(value+flag)%10;
flag=(value+flag)/10;
cur=cur->next;
pre=pre->next;
//还有最高位
if(cur==NULL && flag)
{
struct ListNode* node=(struct ListNode* )malloc(sizeof(struct ListNode* ));
node->val=flag;
node->next=cur;
pre->next=node;
}
}
//翻转
struct ListNode* p=reverse(H->next);
return p;
}
//搞清楚遍历指针指向的是什么,以及在后面加节点是直接接在遍历指针后面还是插在遍历指针前面,还是遍历指针后面有个null,插在遍历指针和null中间。
//当遍历指针本身就等于null,想要赋值,就不能pi-val,得新建新结点赋值,然后插入到遍历指针前面
//碎碎念,仅自己思考