【发布时间】:2021-12-09 14:42:07
【问题描述】:
我遇到了“读取访问冲突”或“分段错误”的错误。
这是我的代码:
#include<iostream>
using namespace std;
class Node {
int data;
public:
Node* next;
Node(int d) :data(d), next(NULL) {}
int getData() {
return data;
}
};
class LinkedList {
Node* head;
Node* tail;
public:
LinkedList() :head(NULL), tail(NULL) {}
void push_front(int data) {
if (head == NULL) {
Node* n = new Node(data);
head = tail = n;
}
else {
Node* n = new Node(data);
n->next = head;
head = n;
}
}
void push_back(int data) {
if (head == NULL) {
Node* n = new Node(data);
tail = head = n;
}
else {
Node* n = new Node(data);
tail->next =n;
tail = n;
}
}
void insert(int data,int pos) {
if (pos == 0) push_front(data);
else {
Node* temp = head;
for (int i = 0; i < pos; i++) {
temp = temp->next;
}
Node* n = new Node(data);
n->next = temp->next;
temp->next=n;
}
}
void print() {
while (head != NULL) {
cout << head->getData() << "=>";
head = head->next;
}
}
};
int main() {
LinkedList l;
l.push_front(5);
l.push_back(8);
l.push_front(0);
l.print();
l.insert(9, 2);
cout << "\n";
}
错误出现在 LinkedList 类中的插入函数中。
实际上一个exception在这个函数中弹出第52行。
我使用 VISUAL STUDIO 2019 作为我的 IDE。 如果有人帮助我解决它,我将非常感激。 我已经查看了这个错误,它是关于我的 temp->next is Null 但现在我不知道如何捕获这个缺陷,因为在初始状态我已经用 Head 初始化了 Next 但除此之外它仍然给出相同的错误。
【问题讨论】:
-
崩溃在
insert函数中。temp是NULL这里:temp = temp->next; -
是的,我知道,但如何解决它告诉我这个
-
print在此处修改head:head = head->next;所以head在完成后指向列表末尾。使用不同的变量来迭代列表。如果print是一个 const 函数,编译器将拒绝不正确的代码。 -
得到它错误已解决非常感谢你
标签: c++ linked-list nodes singly-linked-list