我正在尝试创建一个程序来删除链表第 N 个位置的节点。根据输出,应该是:
George Betty Felix Renee George Betty Felix George Felix Felix
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/