反向链接列表

时间:2016-09-19 00:38:58

标签: c++ data-structures nullpointerexception linked-list

enter image description here这是我得到的输出,如上所示 我是链接列表的新手。我在这里创建一个链接列表并添加节点并尝试反转并打印列表。

这是我的代码:

//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.

有人可以透露这里有什么问题吗?

1 个答案:

答案 0 :(得分: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;
}
}

那将解决它。感谢您的帮助。