2016-09-19 1 views
0

enter image description here 위 출력과 같습니다.
링크드리스트를 처음 사용했습니다. 여기에 연결된 목록을 만들고 노드를 추가하고 목록을 역순으로 인쇄하려고합니다.역방향 연결 목록에 대해 예외 nullptr이 throw됩니다.

//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로 비주얼 스튜디오를 사용하고 있습니다 :

여기 내 코드입니다. 그것은 다음과 같은 오류를 던졌습니다

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

그것은 그것을 고칠 것이다. 모든 도움에 감사드립니다.

관련 문제