2016-11-07 141 views
0

我想在C++中编写我自己的LinkedList应用程序。现在我陷入了困境,我需要一些帮助。我的应用程序触发访问冲突错误,我不知道为什么。 我欣赏任何形式的帮助。当我删除方法“printList()”之后,听 - >删除(0)(现在这个方法只与列表中的1节点工作)其工作,但我想看到输出。如果我再次插入方法printList(),它再次崩溃。C++ LinkedList读取访问冲突错误

这里是我的代码:

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

你的'remove'函数执行不正确。您将在每次调用中删除头节点,而不分配新头或搜索您要删除的内容。 –

+0

我知道这个删除功能不会与更大的列表一起工作。在我的情况下,它唯一打算(现在)由于定位错误而使用1个元素。如果我没有错,我正在删除动态创建的节点与每个电话,而不是头或? – Tjatte

+0

在这种情况下,至少在你的'remove'方法中将'head'指针设置回null(最好是nullptr)。 –

回答

0

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

在实施remove功能的临时实例中,您应该将头指针设置为空。

int LinkedList::remove(int p) { 

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

    return 0; 
}