Question

I am trying to create a simple linklist and add basic functions (add, del, print) but I have trouble with del function, whenever I try to del a node I get this message. "Unhandled exception at 0x00119EC1 in class içine struct.exe: 0xC0000005: Access violation reading location 0x00000004."

LİST.H

#ifndef LIST_H
#define LIST_H


class list{
public:
struct node {

    char data;
    node *next;
};

typedef struct node NodePtr;

NodePtr *head, *current, *temp;

list();
void add(char addData);
void del(char deleteData);
void printList();
void menu();

  };

   #endif

SOURCE.CPP

#include <cstdlib>
#include <iostream>
#include "List.h"

using namespace std;

list::list(){
head = NULL;
current = NULL;
temp = NULL;    
}
void list::add(char addData){

NodePtr *newNode = new NodePtr;
newNode->data = addData;
newNode->next = NULL;
if (head != NULL){

    current = head;
    while (current->next != NULL){
        current = current->next;
    }
    current->next = newNode;
    newNode->next = NULL;
}
else
{
    head = newNode;
}


 }
 void list::printList(){

current = head;

while (current != NULL){
    cout << current->data << endl;
    current = current->next;
}
 }

 void list::del(char deleteData){
NodePtr *delPtr;
delPtr = NULL;
temp = head;
current = head;

while (current != NULL&&current->data != deleteData){
    temp = current;
    current = current->next;
}

if (current = NULL){
    cout << deleteData << "was not in the list" << endl;
    delete delPtr;
}
else
{
    delPtr = current;
    current = current->next;
    temp->next = current;
    if (delPtr == head){
        head = head->next;
        temp = NULL;
    }
    delete delPtr;
    cout << "value" << deleteData << "was deleted" << endl;  
}

 }
 void list::menu(){

cout << "Choose an operation\n"
    << "A: Add Task\n"
    << "S: Search for Task\n"
    << "L: List All Tasks\n"
    << "R: Remove Task\n"
    << "E: Exit\n";

 }

MAİN.CPP

#include <cstdlib>
#include <iostream>
#include "List.h"

using namespace std;

int main(){

char addData, deleteData, operation;
list tasks;
tasks.menu();
cout << "Choose an Operation\n";
cin >> operation;

while (operation!='E' && operation!='e'){

    switch (operation)
    {
    case 'A':case'a':
        cout << "data girin";
        cin >> addData;
        tasks.add(addData);
        break;
    case 'S': case's':
        break;
    case 'L': case 'l': 
        tasks.printList();
        break;
    case 'R': case 'r':
        cin >> deleteData;
        tasks.del(deleteData);
        break;
    default:
        break;
    }
    tasks.menu();
    cin >> operation;



}
}
Was it helpful?

Solution

if (current = NULL){   // it's supposed to be == here
    cout << deleteData << "was not in the list" << endl;
    delete delPtr;
}

OTHER TIPS

if (current = NULL){

most likely should be if (current == NULL){ (note two equal signs). Or perhaps simply if (!current)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top