/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
struct ListNode* FilpLinkList(struct ListNode* phead) //反转链表
{
if(!phead)
return NULL;
struct ListNode* newHead = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode* cur = phead;
newHead->next = phead;
while(cur->next)
{
struct ListNode* temp = cur->next;
cur->next = temp->next;
temp->next = newHead->next;
newHead->next = temp;
}
return newHead->next;
}
struct ListNode* CreatNewNode(int num) //创建新节点
{
struct ListNode* newNode = (struct ListNode *)malloc(sizeof(struct ListNode));
newNode->next = NULL;
newNode->val = num;
return newNode;
}
struct ListNode* addInList(struct ListNode* head1, struct ListNode* head2 ) {
if(head1 == NULL || head2 == NULL) //只要head1、head2有一个为空,就相当于加数为0,直接返回不为空的表头,两个都为空,同理。
return head1 == NULL ? head2 : head1;
struct ListNode* head3 = (struct ListNode*)malloc(sizeof(struct ListNode)); //新建表头
//反转链表
head1 = FilpLinkList(head1);
head2 = FilpLinkList(head2);
struct ListNode* cur1 = head1, *cur2 = head2,*cur3 = head3;
int flag = 0,val1,val2;
while(cur1 || cur2 || flag)
{
//如果cur为空,说明已经走到表尾,直接令val为0即可
val1 = cur1 == NULL ? 0 : cur1->val;
val2 = cur2 == NULL ? 0 : cur2->val;
cur3->next = CreatNewNode((val1 + val2 + flag) % 10); //创建新节点
flag = (val1 + val2 + flag) / 10; //更新flag
cur3 =cur3->next;
//如果cur为空,则停止下滑
cur1 = cur1 == NULL ? NULL : cur1->next;
cur2 = cur2 == NULL ? NULL : cur2->next;
}
return FilpLinkList(head3->next); //翻转新表
}