链表:在给节点的下一部分赋值时出现分段错误

Linked List: Segmentation fault error when assigning a value to the next part of a node

本文关键字:赋值 错误 分段 一部分 节点 链表      更新时间:2023-10-16

这是我在这里的第一个问题,我的英语不是很好,所以请原谅我。

我试图创建一个链表与一个函数来插入一个元素在一定的位置。要做到这一点,我需要定位PREDPTR,但我有麻烦,因为每当我运行程序,我总是得到一个分割错误。我相信错误是在"predptr->next = first;"插入()函数内的部分,但是当我将predptr(上面的行)设置为"predptr = new Node()"时,它可以工作,但它总是触发插入函数中的第二种情况。

代码如下:

//Class List
class List
{
private:
  //Class Node
  class Node
  {
  public:
    string data;
    Node * next;
    //Node constructor
    Node()
    {
      data = "";
      next = 0;
    }
    //Node constructor with value
    Node(string val)
    {
      data = val;
      next = 0;
    }
  };
  int mySize;
  Node * first;
public:
  //List constructor
  List()
  {
    mySize = 0;
    first = 0;
  }
//Insert Function
  void insert(string val, int pos)
  {
    Node * newptr, * predptr;
    newptr = new Node(val);
    predptr = new Node();
    predptr->next = first;
    cout << "Pred: " << newptr->data << endl;
    //Position predptr
    for(int i = 0; i < pos; i++)
      predptr = predptr->next;
    //CASE 1: Inserting at the middle or end of the List
    if(predptr != 0)
    {
      cout << "NF" << endl;
      newptr->next = predptr->next;
      predptr->next = newptr;
    }
    //CASE 2: Inserting at the beginning of the List
    else
    {
      cout << "F"  << endl;
      newptr->next = first;
      first = newptr;
    }
    delete predptr;
    mySize++;
  }
int main()
{
  List a;
  cout << (a.empty() ? "Yes" : "No") << endl;
  cout << "Inserting 5 elements..." << endl;
  a.insert("Asus", 1);
  a.insert("Acer", 2);
  a.insert("Sony", 3);
  a.insert("Toshiba", 4);
  cout << "List A: ";
  a.display();
  cout << endl;
  return 0;
}

可能出现问题的第一个线索将在这里,在insert():

newptr = new Node(val);
predptr = new Node();

逻辑规则规定,如果insert()被期望添加一个值到列表中,那么创建两个新节点,而不是一个,显然是错误的。在这里,您希望只创建一个新节点。不是两个.

insert()中的逻辑是完全错误的。没办法挽回它。这里唯一的选择是从头开始重写:

Node * newptr=new Node(val);
Node **predptr=&first;
while ( (*predptr) && pos)
{
    predptr= & (*predptr)->next;
    --pos;
}
newptr->next= *predptr;
*predptr=newptr;

就是这样。如果pos作为0传入,这将把新节点插入列表中的第一个位置,如果是1,则是第二个,等等……这种性质的东西是基于0的。如果您希望位置#1而不是位置#0作为列表的第一个元素,只需在循环前减少pos

如果pos超过列表的大小,代码不会崩溃,不像你的尝试,只是添加新的节点到列表的末尾。

我将以引号结束:

"你对管道考虑得越多,就越容易堵塞。下水道。"

史考特,《星际迷航3》

插入链表是一个简单的操作。这不应该是一个复杂的过程。