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

标签 c++

我正在尝试创建一个程序来删除链表第 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/

相关文章:

c++ - 将模板函数作为参数传递给 C++ 中的另一个函数时出现问题

c++ - 如何找出std::vector中是否存在某个元素?

c++ - 是否可以将 for(auto i=0;i<n;i++) ... 替换为 for(auto i :<something>) without using a vector?

c++ - C++嵌套if语句,基本货币兑换

c++ - 以分布式方式枚举组合

c++ - 在 lambda 比较器中使用捕获

c++ - 如何将库 curlpp 添加到 C++ 项目

c++ - 使用 pthread 和引用保护 C++ 类

c++ - 使用 C++ 从给定精确坐标的图像中裁剪矩形

c++ - 读取一个txt文件显示异常