gpt4 book ai didi

c++ - 为什么每当我尝试运行此 LinkedList 删除函数时都会收到段错误错误?

转载 作者:行者123 更新时间:2023-12-01 14:47:32 26 4
gpt4 key购买 nike

我正在尝试创建一个程序来删除链表第 N 个位置的节点。根据输出,它应该是:

GeorgeBettyFelixReneeGeorge BettyFelixGeorgeFelixFelix

When running on repl.it (my submission website), it brings up that I am getting a segmentation error. However, when I run it off my personal computer on CodeBlocks, it runs without errors, however, it only outputs the first line which is George, Betty, Felix, and Renee without deleting and re-outputting.

Here's my code:

#include <iostream>
#include <string>

using namespace std;

class Node {
public:
string name;
Node* next;
};

Node* head;

class LinkedList {
public:
LinkedList();
~LinkedList();
void push(string);
void output();
void remove(int);

private:
Node *first;
};


void LinkedList::remove(int n)
{
struct Node* temp1 = head;
if(n == 1)
{
head = temp1 -> next;
delete(temp1);
return;
}
int i = 0;
for(i = 0; i < n - 2; i++)
{
temp1 = temp1 -> next;
}
struct Node* temp2 = temp1 -> next;
temp1 -> next = temp2 -> next;
delete(temp2);

}


LinkedList::LinkedList()
{
first = NULL;
}

LinkedList::~LinkedList()
{
Node *current=first;

while(current!=NULL)
{
Node *ptr=current;
current = current->next;
delete(ptr);
}
}

void LinkedList::push(string data)
{
Node *temp;

temp = new Node;
(*temp).name = data;
(*temp).next = first;
first = temp;
}

void LinkedList::output()
{
Node *current = first;

while(current!=NULL)
{
cout << (*current).name << endl;
current = (*current).next;
}
cout << endl;
}

int main() {
LinkedList students;

students.push("Renee");
students.push("Felix");
students.push("Betty");
students.push("George");


students.output();

students.remove(3);
students.output();

students.remove(1);
students.output();

students.remove(0);
students.output();


}

最佳答案

除了 LinkedList::remove 之外的所有代码通过 first 管理列表成员变量。但是LinkedList::remove引用 head ,一个可疑的未使用的全局变量。我相信这根本不应该出现在代码中。

删除全局 head ,并更改 LinkedList::remove成为:

void LinkedList::remove(int n)
{
Node **pp = &first;
while (*pp && n-- > 1)
pp = &(*pp)->next;

if (*pp)
{
Node *tmp = *pp;
*pp = tmp->next;
delete tmp;
}
}

关于c++ - 为什么每当我尝试运行此 LinkedList 删除函数时都会收到段错误错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62459947/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com