力扣第二题的完整实现代码

RT,我分别给两个链表赋值后,再用addtwonumbers调用,但是不知道为啥会显示乱码。

img

#include "stdc++.h"
using namespace std;
struct ListNode {
int val; //变量
ListNode* next; //定义下个节点
ListNode() : val(0),next(NULL) {} //初始化
ListNode(int x) : val(x), next(nullptr) {} //赋值
ListNode(int x, ListNode* next) : val(x), next(next) {} //赋值+建新节点
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* H = new ListNode();
ListNode* p = H;
int carry = 0;
while (l1 || l2 || carry)
{
int val = 0;
if (l1) val += l1->val, l1 = l1->next;
if (l2) val += l2->val, l2 = l2->next;
val += carry;
carry = val / 10;
ListNode* temp = new ListNode(val % 10);
p->next = temp;
p = p->next;
}
return H->next;
}
};
void creat(ListNode* L) {
int cur=0;
while (cur != -1) { //当输入为-1时结束
cin >> cur;
if (cur == -1) break;
else {
ListNode* ptr = new ListNode; //申请空间
ptr->val = cur;
ptr->next = NULL;
L->next = ptr; //与链表链接
L = L->next;
}
}
}
void printList(ListNode* L) {

     while(L->next) {
         cout << L->next->val;
         L = L->next;
     }
 

}
int main() {
ListNode* a=new ListNode;
ListNode* b = new ListNode;
Solution l;
creat(a);
creat(b);
cout<<l.addTwoNumbers(a, b);
}

咨询一下自己解决是不是可以不算

已经解决了,那个addTwoNumbers只会输出一个数字,所以需要再new一个链表输出。
int main() {
ListNode* a = new ListNode;
ListNode* b = new ListNode;
Solution l;
creat(a);
creat(b);
ListNode* H = l.addTwoNumbers(a, b);
printList(H);
}
10块大洋换来的答案,害。