函数与返回类型 node* 与 C++ 中的 OOP 结合使用

function with return type node* in conjunction with OOP in c++

本文关键字:OOP 结合 中的 C++ 返回类型 node 函数      更新时间:2023-10-16

我需要编写一个程序,该程序采用线性链表的实例并删除列表中除最后两个项目之外的所有项目。我使用类在 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();
}