Function to delete item from hashtable not deleting or generating error message

Hello,

I am trying to write a function to delete an item from a hashtable chained with a linked list. To do so, it is my understanding that it's just a matter of re-directing the links to the node for the item to be deleted to bypass that node. I am however getting a read access violation at the point it tries to print the item that is to be deleted. It doesn't delete the item, it just replaces its value with "garbage", "hangs" then generates the error message.

If someone could look at it and give me some feedback as to what could be wrong, I would appreciate it. Here is the code to the function:

void MyChain::deleteItem(int val)
{
int location = (val % arraySize); //hash function
nodeType *link;
nodeType *trailCurrent; //pointer just before current
nodeType *current;
nodeType *first = hashtable[location]; //pointer to traverse the list
nodeType *last = nullptr;
if (first == NULL)
cout << "Cannot delete from an empty list." << endl;
else
{
if (first->info == val)
{
current = first;
first = first ->link;

if (first == NULL)
last = NULL;
delete current;
}
else
{
trailCurrent = first;
current = first->link;
while (current != NULL)
{
if (current->info != val)
{
trailCurrent = current;
current = current->link;
}

else if (current->info == val)
{
trailCurrent->link = current->link;
if (last == current)
last = trailCurrent;
delete current;
}
else
cout << "The item to be deleted is not in the list." << endl;
}
}
}
}

Here is the rest of the code:

using namespace std;

struct nodeType
{
int info;
nodeType *link;
nodeType *next;
};

class MyChain
{
public:
void print() const; //Print the values of the hashtable
void push(int); //Insert value into hashtable
void deleteItem(int); //Remove value from hashtable
MyChain(); //Constructor

private:
int arraySize;
nodeType *hashtable[100];
};

MyChain::MyChain()
{
arraySize = 100;
for (int i = 0; i < arraySize; i++)
{
hashtable[i] = nullptr;
}
}

void MyChain::push(int val)
{
int location = val % arraySize;
nodeType *toInsert = new nodeType;
toInsert->link = NULL;
toInsert->info = val;

if (hashtable[location] == NULL)
{
hashtable[location] = toInsert;
}
else
{
nodeType *entry = hashtable[location];
while (entry->link != NULL)
{
entry = entry->link;
}
entry->link= toInsert;
toInsert->info = val;
}
}

void MyChain::print() const
{
nodeType *current;

for (int i = 0; i < arraySize; i++)
{
current = hashtable[i];
int pointerCounter = 0;
while (current != NULL)
{
cout << "Position [" << i << "]";
cout << "[" << pointerCounter << "]";
cout << current->info << " " <<endl;
current = current->link;
pointerCounter++;
}
}
}

int main()
{

MyChain newChain;

newChain.push(5);
newChain.push(11);
newChain.push(24);
newChain.push(51);
newChain.push(106);
newChain.push(5);
newChain.push(9);

newChain.print();

newChain.deleteItem(5);

newChain.print();
}

Any guidance is appreciated.

Thanks!

Ragan
Topic archived. No new replies allowed.