[英]Null Pointer exception while using Linked List in c++
我有“读取访问冲突”或“分段错误”的错误。
这是我的代码:
#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 类中的插入函数中。
实际上,此函数中的第 52 行会弹出一个异常。
我使用VISUAL STUDIO 2019作为我的 IDE。 如果有人帮助我解决它,我将非常感激。 我查看了这个错误,它是关于我的 temp->next is Null 但现在我不知道如何捕捉这个缺陷,因为在初始状态我已经用 Head 初始化了 Next 但除此之外它仍然给出相同的错误。
当你插入到最后一个位置时,像在 push_back() 中一样处理它。
编辑:我没有注意到你修改了打印函数中的头指针......这是根本原因,正如@retired-ninja 所指出的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.