在单向链表的指针中引发异常



好的,我使用 Node 类和 List 类创建了一个链表。但是每当我使用 List 对象运行它时,当我在Node.cpp中返回getHead()函数中的head时,它会引发异常 这些是我创建的文件,如果有人知道为什么会出现此异常,那将是一种祝福

//**NODE.h**
#include<iostream>
using namespace std;
class Node{
private:
Node* head;
int data;
public:
Node();
Node(int);   //insert data
void setHead(Node*);
Node* getHead();
void setData(int);
int getData();
void printData(Node*);
};
//**Node.cpp**
#include"Node.h"
Node::Node(){
//Node* head = new Node();
head = NULL;
data = 0;
}
Node::Node(int DATA){
//Node* head = new Node();
head = nullptr;
data = DATA;
}
int Node::getData(){            //DATA SETTER
return this->data;
}
void Node::setData(int DATA){   //DATA GETTER
this->data = DATA;
}
Node* Node::getHead(){          
return head;
}
void Node::setHead(Node* NextAddress){
this->head = NextAddress;
}
void Node::printData(Node* node){
while(node != nullptr){
cout<< this->data <<"n";
node = node->head;
}
}
//**List.h**
#include"Node.h"
class List : public Node{
private:
Node* head;
Node* current;
Node* prevcurrent;
public:
List();
//void setList(int);
void insertAtBack(Node* , int);
void insertAtFront(Node* , int);
bool search(int);
void print();
~List();
};
//**List.cpp**
#include"List.h"
List::List(){
head=nullptr;
current=nullptr;
prevcurrent=nullptr;
}
void List::insertAtBack(Node* head , int Data){
Node* newNode = new Node();
newNode->setData(Data);
newNode->setHead(head);     //sets the address of the next node into the newly added node
head = newNode;
}

void List::insertAtFront(Node* head, int Data) {
Node* temp = new Node();
}
bool List::search(int num){
Node* temp = head;   
while (temp->getHead()!=nullptr)
{
if (temp->getData() == num)
{
return true;
}
temp->setHead(temp->getHead());     //itereates the adress in the emp node to store the address of the next node fro the while loop
}

}
void List::print(){
Node* temp=head;
while (temp->getHead() != nullptr)
{
cout<<temp->getData()<<" ";
}

}
List::~List() {
Node* temp = head;
while (temp->getHead() != nullptr)
{
Node* temp2 = temp;
temp = temp->getHead();
delete temp2;
}
}
//**main.cpp**
#include"List.h"
int main(){
// cout<<"runningn";
// Node box(5);         this works
// cout<<box.getData();
List obj;
Node node;              //this will throw an exception
obj.insertAtBack(&node,5);
obj.print();
}

由于打印而引发异常:

void List::print() {
Node *temp = head;
while (temp->getHead() != nullptr) {
cout << temp->getData() << " ";
}
}

在这里,如果在temp(或同样head)是 nullptr 之前,则缺少检查temp->getHead()

List::~List也一样

最新更新