函数与返回类型 node* 与 C++ 中的 OOP 结合使用
function with return type node* in conjunction with OOP in c++
我需要编写一个程序,该程序采用线性链表的实例并删除列表中除最后两个项目之外的所有项目。我使用类在 c++ 中执行此操作,所以我将有 3 个文件:main.cpp、list.h 和 list.cpp。不能有循环:我可以使用多个函数,但遍历部分必须是递归的。
我想了想,我得出的结论是:我必须有一个可以从main调用的公共函数,它不需要参数,称为void lastTwo((。我将有另一个名为node* lastTwo(node *& current,node *& tail(的私有函数,它将由lastTwo((调用,它将递归遍历列表并删除它接触的节点,直到它到达列表中的倒数第二个节点,然后它将返回该节点的地址。
然后,当它返回列表中倒数第二个节点的地址时,公共函数lastTwo((将捕获该地址并将head设置为等于它。
我遇到的问题是我需要在 vi 中执行此操作并从命令行编译和运行,即使我绘制了指针图并且找不到代码问题,我也遇到了分段错误。
我正在我大学的学生服务器上处理这个问题,除了这两个函数之外,数据结构的所有实现都是由我的老师编写的,所以它们都是可靠的。此外,每次运行 a.out 文件时,他们都会将其写入以生成至少 5 个节点的新、随机、非空链表。
我认为问题与具有返回类型"node*"的函数有关,因为我也尝试在 Visual Studio 中执行此操作,但它不允许我拥有 node* 类型的函数。但是,我知道当你不使用类而只是将所有内容放在一个文件中时,node* 类型的函数就可以工作了。
这是我的清单.h:
#include<iostream>
struct node
{
int data;
node* next;
};
class list
{
public:
// these functions were already written by the school and included in the .o file
list();
~list();
void build();
void display();
// my functions
void lastTwo();
private:
node* head;
node* tail;
node* lastTwo(node *& current, node *& tail);
}
并列出.cpp:
void list::lastTwo(){
node* current = head;
node * newHead = lastTwo(current, tail);
head = newHead;
delete newHead;
head->next = tail;
}
node* lastTwo(node *& current, node *& tail){
if(current->next == tail){
return current;
}
else if(current->next != tail){
node* temp = current;
current = current->next;
temp->next = NULL;
delete temp;
lastTwo(current, tail);
}
return NULL;
}
任何关于可能是什么问题的想法,以及正确的方法是什么,将不胜感激!谢谢
当你的递归展开时,你的问题就会发生。大多数lastTwo
电话都发生在else if
。该基本情况是返回当前情况的if
,但触发基本情况的对lastTwo
的调用在else if
结束时始终会返回NULL
。
想象一下,当达到基本情况时,这是您的堆栈:
lastTwo // Base case, returns current, but the call below this doesn't do anything with it.
lastTwo // returns null
...
lastTwo // returns null
该 NULL 被其他lastTwo
使用,并且您会出现 seg 错误。
您可以使用以下内容:
void list::lastTwo() {
// Stop work with less than 2 items
if (head == nullptr // 0 items
|| head == tail // 1 item
|| head->next == tail) { // 2 items
return;
}
// pop_front()
auto* next = head->next;
delete head;
head = next;
// loop
lastTwo();
}
- 多态性和功能结合
- c++中的oop(密码生成)
- OOP 中的单成员指针
- 将 Vulkan 与 SFML 结合使用?
- 将 c++ 生成器应用程序与外部 dll 结合使用
- 如何将增强MSM与增强信号结合使用?
- MS Visual Studio 解决方案结合了非托管C++项目和 C# 项目
- OOP使用不同的结构与孩子一起构建建议
- OOP 标识派生对象
- 函数未在作用域中声明 / 如何结合使用 header.h、header.cpp 和 main.cpp?
- 标识符Class_name未定义C++ oop
- 返回类型在 C++ OOP 中是什么意思
- 将预编译的 C 共享库与 JNI/NDK 结合使用
- 这里的以下 OOP 结构是什么?
- C++ 将函数指针与最佳性能相结合
- 将 Lua 与 C++ DLL 结合使用
- 为什么push_back和emplace_back结合在一起时,会有不同的行为
- 将 aws-iot-device-sdk-cpp-v2 与 CMake 结合使用
- 函数与返回类型 node* 与 C++ 中的 OOP 结合使用
- 难以将 GP 和 OOP 概念结合起来