2016-09-19 34 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; 
} 

我使用Visual Studio爲我的IDE。它會拋出錯誤,因爲

Exception thrown: write access violation. 
temp was nullptr. 

有人能請揭示這裏出了什麼問題嗎?

+0

'Node * temp = NULL; //創建一個新節點'不,它不會創建一個新的節點。 – songyuanyao

+0

@songyuanyao但是那是我聲明瞭一個名爲temp的節點指針,它被初始化爲NULL –

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

這將解決它。感謝所有的幫助。