链表:在给节点的下一部分赋值时出现分段错误
Linked List: Segmentation fault error when assigning a value to the next part of a node
这是我在这里的第一个问题,我的英语不是很好,所以请原谅我。
我试图创建一个链表与一个函数来插入一个元素在一定的位置。要做到这一点,我需要定位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》
插入链表是一个简单的操作。这不应该是一个复杂的过程。
相关文章:
- 使用 mat.at<uchar>(i,j) 的 opencv C++中的矩阵赋值错误
- C++:构造函数中的向量赋值错误
- 两个向量赋值错误
- 需要左值作为赋值错误的左操作数通过 if 语句
- 左值和右值赋值错误
- 在 C++ 中需要左键作为赋值错误的左操作数
- 分配不同类对象时出现赋值错误
- 从字符串数组打印其中一个字符串时出现空指针赋值错误
- 如果我分配给彼此的两个变量都是字符串类型,为什么我会收到这个strcpy赋值错误
- 赋值错误中的非左值
- R 值重载运算符字符串赋值错误
- 加法和赋值错误
- 使用C++时,赋值错误的左操作数需要左值
- 如果右手边包含字符串文字的串联,则C++const std::字符串赋值错误
- c++奇怪的ifstream重赋值错误
- 赋值错误的左操作数需要左值
- Mat OpenCv的赋值错误
- 字符串赋值错误
- Std::swap只读引用赋值错误
- 在子类类中重载基类赋值操作符会导致二义性赋值错误