2016-11-07 140 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; 
}