C ++ LinkedList读访问冲突错误

时间:2016-11-07 01:47:38

标签: c++ crash

我正在尝试用C ++编写自己的LinkedList应用程序。现在我被困在一个需要帮助的地步。我的应用程序正在触发访问冲突错误,我不知道为什么。 我感谢任何帮助。当我删除方法" printList()"听完后 - > remove(0)(现在这个方法只与列表中的1个节点一起工作)它的工作,但我想看看输出。如果我再次插入方法printList(),它会再次崩溃。

这是我的代码:

LinkedList.cpp

#include "LinkedList.h"
#include <iostream>

LinkedList::LinkedList() {
    head = NULL;
    tail = NULL;
}

LinkedList::~LinkedList() {
    std::cout << "Die Liste wurde aus dem Speicher gelöscht.";
}

int LinkedList::append(const char* text) {
    //new Node
    Node* node = new Node();
    node->setData(text);
    node->setNext(NULL);

    //temp pointer
    Node* tmp = head;
    if (tmp == NULL) {
        //List empty && set first node to head
        head = node;
    } else {
        //list not empty, find the end of the list
        while (tmp->getNext() != NULL) {
            tmp = tmp->getNext();
        }
        tmp->setNext(node);
    }
    return 0;
}

int LinkedList::remove(int p) {
    int counter = 0;
    //temp pointer
    Node* node = head;
    delete node;
    return 0;
}

void LinkedList::printList() {
    Node* node = head;
    if (node == NULL) {
        std::cout << "Empty";
    } else if (node->getNext() == NULL) {
        //only one node in the list
        std::cout << node->getData() << " --> NULL" << std::endl;
    } else {
        do {
            std::cout << node->getData() << " --> ";
            node = node->getNext();
        } while (node != NULL);
        std::cout << "NULL" << std::endl;
    }
}

node.cpp

#include "node.h"
#include <iostream>

Node::Node() {
    //NOTHING
}

Node::~Node() {
    std::cout << "Node aus Speicher gelöscht.";
}

void Node::setData(const char* d) {
    data = d;
}

void Node::setNext(Node* n) {
    next = n;
}

const char* Node::getData() {
    return data;
}

Node* Node::getNext() {
    return next;
}

的main.cpp

#include "LinkedList.h"

int main() {
    LinkedList* liste = new LinkedList();
    liste->printList();
    liste->append("10");
    liste->printList();
    liste->remove(0);
    liste->printList();
    return 0;
}

1 个答案:

答案 0 :(得分:0)

在“有限范围”remove函数中,删除头节点(通过node变量)。这意味着下次尝试打印列表时,您将尝试使用已删除的值,因此会调用未定义的行为。

在为一般情况实现remove函数之前的过渡期间,您应该将头指针设置为null。

int LinkedList::remove(int p) {

    if(head){
        delete head;
        head = nullptr;
    }

    return 0;
}
相关问题