2016-09-19 5 views
0

enter image description hereこれは、上記のように出力されます。
リンクされたリストを初めて使用しています。私はリンクされたリストを作成してノードを追加し、リストを逆にして印刷しようとしています。リバースリンクリストに対して例外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; 
} 

は私が私のIDEとしてのVisual Studioを使用しています:

は、ここに私のコードです。それはエラーをスローする

Exception thrown: write access violation. 
temp was nullptr. 

誰かがここで何が間違っているのか教えてください。

+0

'Node * temp = NULL; //新しいノードを作成する 'いいえ、新しい' Node'を作成しません。 – songyuanyao

+0

@songyuanyaoしかし、それはNULLに初期化されたtempという名前のノードポインタを宣言しています。 –

+0

'Node'を構築しなかったので、' temp'はヌルポインタです。 'temp-> data'は動作しません。 – songyuanyao

答えて

0

上記の修正が済んだら、単に貼り付けをコピーするだけでaddNode関数を変更する必要があります。それは次のようになります。

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; 
} 
} 

これで解決します。すべての助けに感謝します。

関連する問題