提交 b4d7ff01 编写于 作者: cosmicing's avatar cosmicing

上传新文件

上级 15c722ab
#include <iostream>
// Definition for singly-linked list.
struct ListNode
{
int val;
ListNode *next;
ListNode(int x) : val(x), next(nullptr) {}
};
class Solution
{
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* dumHead = new ListNode(0);
ListNode* p = dumHead;
int add = 0;
while (l1 || l2 || add)
{
int val = get_value(l1) + get_value(l2) + add;
add = val / 10;
p->next = new ListNode(val % 10);
p = p->next;
l1 = get_p(l1);
l2 = get_p(l2);
}
ListNode* ret = dumHead->next;
delete dumHead;
return ret;
}
private:
int get_value(ListNode* l)
{
if (l != nullptr)
{
return l->val;
}
else
{
return 0;
}
}
ListNode* get_p(ListNode* l)
{
if (l != nullptr)
{
return l->next;
}
else
{
return nullptr;
}
}
};
void deleteListNode(ListNode *l1)
{
while (l1 != nullptr)
{
ListNode* p = l1->next;
delete l1;
l1 = p;
}
}
int main()
{
ListNode *l1 = new ListNode(0);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
ListNode *l2 = new ListNode(0);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
ListNode * ret = Solution().addTwoNumbers(l1, l2);
while (ret != nullptr)
{
std::cout << ret->val << std::endl;
ret = ret->next;
}
deleteListNode(l1);
deleteListNode(l2);
deleteListNode(ret);
return 0;
}
\ No newline at end of file
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册