【发布时间】:2021-08-29 05:36:05
【问题描述】:
我为链表编写了一个类,在这个类中我编写了如下函数: 将值为 val 的节点附加到链表的最后一个元素,在链表的第一个元素之前添加一个值的节点等等...
我要解决这个问题:https://leetcode.com/problems/add-two-numbers/
在这个问题中,给出了函数的签名:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
这是我编写的类,其中包含 ListNode 结构。这些是本示例的最小函数。
class MyLinkedList {
public:
/** Initialize your data structure here. */
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* head;
ListNode* tail;
int size;
MyLinkedList() {
this->head = nullptr;
this->tail = nullptr;
this->size = 0;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
void addAtHead(int val) {
ListNode* temp = new ListNode(val);
if (this->head == nullptr) {
this->head = temp;
this->tail = temp;
}
else {
temp->next = this->head;
this->head = temp;
}
this->size++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
ListNode* temp = new ListNode(val);
if (this->tail == nullptr) {
this->head = temp;
this->tail = temp;
}
else {
this->tail->next = temp;
this->tail = temp;
}
this->size++;
}
};
我正在使用 VS Code,在我编写 main 函数的同一个文件中:
int main()
{
MyLinkedList* l1 = new MyLinkedList();
MyLinkedList* l2 = new MyLinkedList();
// l1 = [2,4,3]
l1->addAtHead(2);
l1->addAtTail(4);
l1->addAtTail(3);
// l2 = [5,6,4]
l2->addAtHead(5);
l2->addAtTail(6);
l2->addAtTail(4);
}
在主函数中我不知道如何访问类内的结构,因为解决方案的功能超出了main() 的范围和类之外。
我不知道哪个类型需要是l3 这样l3 = l1 + l2 和我将使用相同的函数签名:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
================================================ =================
如果我只使用网站上问题给出的结构,没有类,我将main() 更改为:
struct ListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
int main()
{
ListNode* l1 = new ListNode(2);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
ListNode* l2 = new ListNode(5);
l2->next = new ListNode(6);
l2->next->next = new ListNode(7);
ListNode* l3 = addTwoNumbers(l1, l2);
}
所以一切正常。
我的问题是如何使用我编写的类通过使用我的类中的函数来创建链接列表,并使用它们来调用函数:ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 以返回解决方案。
谢谢。
【问题讨论】:
-
请尝试完全重写您的问题,重点是您实际问题的抽象版本,而不是您的完整程序。您的代码可能应该被削减为 minimal reproducible example 以表明您的具体问题。对How to Ask 的评论可能会有所帮助。