每当尝试运行此LinkedList删除功能时,为什么会出现分段错误错误?

攀岩者

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

乔治·
贝蒂
费利克斯·
蕾妮

乔治·
贝蒂
费利克斯·

乔治·
费利克斯·

费利克斯

在repl.it(我的提交网站)上运行时,它提示我遇到了细分错误。然而,当我可以坚持的代码块我的个人电脑,它运行没有错误,但是,它只是输出的第一行是GeorgeBettyFelix,和Renee而不删除并重新输出。

这是我的代码:

#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();


}
WhozCraig

除了 LinkedList::remove通过first成员变量管理列表之外,所有代码都适用但是LinkedList::removereference head,一个可疑的未使用的全局变量。我有信心甚至根本不在代码中。

删除global 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;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

在C Linux中使用共享内存尝试IPC时为什么会出现分段错误

为什么运行此代码时出现分段错误?

当我尝试运行Anaconda Navigator时出现分段错误

为什么会出现此错误?-分段错误(核心已转储)

为什么在尝试运行fab模块时出现语法错误?

尝试访问功能时出现分段错误

尝试重新启动井字游戏时,为什么会出现此错误?

React App:为什么在尝试运行npm start脚本时出现错误?

我正在尝试使用Foundation scss建立一个新网站,但是,每次我尝试运行sass时,都会出现此错误

尝试在列表中插入字符串时为什么会出现此错误?

每当我尝试运行此代码时,都会出现类似“错误:在行附近解析错误”的错误消息,但我不知道该怎么办?

为什么运行此功能时出现类型错误?

尝试运行iptables rhel6时出现分段错误(内核已转储)

尝试检查是否在Corona SDK中时为什么会出现此错误?

尝试运行JUnit测试时,为什么会出现“在使用ClassLoader搜索持久性归档时抛出异常”错误?

尝试运行Arduino时出现错误

为什么每当我将API密钥放入build.gradle时都会出现运行时错误?

为什么会出现分段错误?

为什么更改此代码时会出现“分段错误”错误?

当我尝试运行此程序时出现分段错误错误

当我尝试在 VueJS 中加载组件时,为什么会出现此错误?

尝试运行统一游戏时出现此错误

为什么会出现此分段错误?

当我尝试使用 pip 安装 autopep8 时,为什么会出现此错误?

为什么每次尝试运行 VS Code python 终端时都会出现语法错误?

为什么在尝试发送电子邮件时使用 phpmailer 会出现此错误?

当我尝试从数据库创建模型时,为什么会出现此错误?

为什么此代码段会出现分段错误?

当我尝试在 Button(action: {}) 中键入 Text() 或 Image() 时,为什么会出现此错误?