Это результат, который я получаю, как видно выше.
Я новичок в Linked Lists. Я здесь создаю связанный список и добавляю узел и пытаюсь перевернуть и распечатать список.Исключение nullptr выбрано для обратного связного списка
Вот мой код:
//this is my PracImplement header file
#include <iostream>
using namespace std;
class Node {
public:
Node();
~Node();
int data;
Node* next;
};
class PracNImplement
{
public:
PracNImplement();
~PracNImplement();
void addNode(int);
void reverseList();
void printList();
void testList();
private:
Node* top = NULL;
};
//this is my PracImplement cpp file
#include "PracNImplement.h"
using namespace std;
Node::Node() {
//default constructor
}
Node::~Node() {}
PracNImplement::PracNImplement()
{
//default constructor
top = NULL;
}
PracNImplement::~PracNImplement()
{
// destructor
}
void PracNImplement::addNode(int val) {
Node* temp = new Node(); //creating a new node
temp->data = val;
temp->next = NULL;
if (top == NULL) {
top = temp; //checking the head or else feel with data(val)
}
else {
Node* temp1 = top;
while (temp1->next != NULL){
temp1 = temp1->next;
temp1->next = temp;
}
}
}
void PracNImplement::reverseList() {
Node* n1 = top;
Node* n2 = NULL;
Node* n3 = NULL;
while (n1 != NULL) {
top = n1;
n2 = n1->next;
n1->next = n3;
n3 = n1;
n1 = n2;
}
}
void PracNImplement::printList() {
Node* temp = top;
while (temp != NULL) {
cout << temp->data << endl;
temp=temp->next;
}
cout << endl;
}
//This is my test function
int main(){
PracNImplement* ttl = new PracNImplement();
ttl->addNode(20);
ttl->addNode(21);
ttl->addNode(22);
ttl->addNode(23);
ttl->addNode(24);
ttl->addNode(25);
cout << "The current list has the following items: " << endl;
ttl->printList();
ttl->reverseList();
cout << "This is the reversed list items: " << endl;
ttl->printList();
delete ttl;
}
Я использую Visual Studio, как мой IDE. Он выдает ошибку как
Exception thrown: write access violation.
temp was nullptr.
Не могли бы вы сообщить, что здесь не так?
'Узел * temp = NULL; // создание нового узла. Нет, он не создает новый «узел». – songyuanyao
@songyuanyao, но это я объявляю указатель узла с именем temp, который инициализирован NULL –
Вы не создали 'Node',' temp' - нулевой указатель, тогда 'temp-> data' не будет работать. – songyuanyao