i am trying to write my own LinkedList Application in C++. Right now i am stucked at a point where i need some help. My Application is triggering an access violation error and i dont know why. I appreciate any kind of help. When i delete the method "printList()" after liste -> remove(0) (right now this method is working with only 1 node in the list) its working, but i want to see the output. If i insert the method printList() once again, its crashing again.
Here is my code:
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;
}
In your 'limited scope' remove
function you delete the head node (via the node
variable). This means that next time you try to print the list, you are trying to use a value that has been deleted and therefore are invoking undefined behaviour.
In the interim before you implement your remove
function for the general case you should set the head pointer to null.
int LinkedList::remove(int p) {
if(head){
delete head;
head = nullptr;
}
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.