【发布时间】:2020-12-15 11:24:16
【问题描述】:
给定两个代表两个非负整数的非空链表。这些数字以相反的顺序存储,它们的每个节点都包含一个数字。将两个数字相加并作为链表返回。
例子:
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
vector<int> a1;
vector<int> a2;
vector<int> result;
while(l1->next||l2->next)
{
a1.push_back(l1->val);
a2.push_back(l2->val);
l1=l1->next;
l2=l2->next;
}
int v1=0;
int v2=0;
for(auto d:a1)
{
v1=v1*10+d;
}
for(auto f:a2)
{
v2=v2*10+f;
}
int v3=v1+v2;
int r;
while(v3>0)
{
r=v3%10;
v3=v3/10;
result.push_back(r);
}
ListNode* p= new ListNode(result[0]);
ListNode* start=p;
ListNode* add=p;
int i;
for(i=1;i<result.size();i++)
{
ListNode* temp=new ListNode(result[i]);
add->next=temp;
add=add->next;
}
return p;
}
};
Output(1st element of the linked list is not printing)
Input: [2,4,3]
[5,6,4]
Your answer:[0,8]
Expected answer:[7,0,8]
我无法打印结果链表的第一个元素。我尝试了不同的测试用例,除了第一个元素之外,它打印的所有内容都正确。
【问题讨论】:
-
for(i=1; ...-->for(i=0; ...? -
您会很高兴听到您不需要任何人的帮助来解决这个问题,只需一个您已经拥有的工具:您的调试器!这正是调试器的用途。它一次一行地运行你的程序,并向你展示正在发生的事情。了解如何使用调试器是每个 C++ 开发人员必备的技能,没有例外。在调试器的帮助下,您应该能够快速找到此程序以及您编写的所有未来程序中的所有错误,而无需向任何人寻求帮助。您是否已经尝试过使用调试器?如果不是,为什么不呢?您的调试器向您展示了什么?
-
当我更改 i=0 时,它在开始时打印 0 @cigien
-
我现在一定会试一试@SamVarshavchik
标签: c++ algorithm c++11 data-structures linked-list