
一、题目描述

二、算法原理

三、代码实现
cpp
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
#include <bits/types/struct_tm.h>
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
ListNode* addInList(ListNode* head1, ListNode* head2) {
ListNode* prev1 = nullptr;
ListNode* prev2 = nullptr;
ListNode* tmphead1 = nullptr;
ListNode* tmphead2 = nullptr;
while(head1 || head2)//翻转这两个链表
{
if(head1)
{
tmphead1 = head1->next;
head1->next = prev1;
prev1 = head1;
head1 = tmphead1;
}
if(head2)
{
tmphead2 = head2->next;
head2->next = prev2;
prev2 = head2;
head2 = tmphead2;
}
}
ListNode* cur1 = prev1,*cur2 = prev2;
int t = 0;
ListNode* head = new ListNode(0);
ListNode* node = head;
while(cur1 || cur2 || t)//对这两个链表进行加法运算
{
if(cur1)
{
t += cur1->val;
cur1 = cur1->next;
}
if(cur2)
{
t += cur2->val;
cur2 = cur2->next;
}
ListNode* tmp = new ListNode(t % 10);
node->next = tmp;
node = tmp;
t /= 10;
}
ListNode* prev_node = nullptr;
ListNode* cur = head->next;
ListNode* tmpnode = nullptr;
while(cur)//再翻转回来
{
tmpnode = cur->next;
cur->next = prev_node;
prev_node = cur;
cur = tmpnode;
tmpnode = nullptr;
}
return prev_node;
}
};