Remove node by value (hash table using chaining)

I'm working on a school project, and I'm having some trouble identifying all of my potential deletion points for my remove function. I thought I had everything working ok, but if the node being removed is not in the middle, I end up with errors. This is the first time I've worked with tables, so I'm finding the whole process to be a bit daunting.

In the project, we are using an array of pointers to separate linked lists. The information is organized by topic, each topic has its own LLL in the array. The remove function needs to locate every possible value match across all of the lists in the array. I have managed to do this part, but I am only successful with removing all the correct nodes without error if they are in the middle.

I'm wondering if someone could help me identify where I might be running into trouble.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// remove by value
bool Table::removeByVal()
{
	int value = 0;
	int i = 0;
	bool flag = false;

	Node *prev = nullptr;
	Node *delPtr = nullptr; // deletion pointer
	
	// check each array member for a list
	for (i = 0; i < capacity; i++)
	{
		Node *curr = table[i];
		
		while (curr != nullptr) 
		{
			value = curr->item.getValue();
	
			if (value == 1)
			{
				delPtr = curr; // delete this data 

				if (prev != nullptr) // deletion here seems to be ok
				{
					prev->next = curr->next;
					delete delPtr;
					curr = prev->next;
				}
				else
				{
					table[i] = curr->next;
					delete curr;
					curr = table[i];
				}
				flag = true;
			}
			else
			{
				prev = curr;
				curr = curr->next;
			}
		}
	}
	return flag;
}

You are running into trouble when you delete a pointer without removing it from the table (line 27/33). This way you have a mix of valid and invalid data in that array.

If you want to keep that array I would suggest that you don't store pointers in your list but indexes.
I was able to fix the issue by scrapping the deletion pointer so that I am only working with curr and prev (to avoid confusion) and then reassigning curr to the table after it has been deallocated. This seems to have resolved all of my issues. I have checked all the possible list positions I can think of including having to delete all the lists in the table. I no longer have any exceptions being thrown and I show no memory leaks.

Thanks for your help!

1
2
3
4
5
6
7
8
if (prev != nullptr)
{
	prev->next = curr->next;
	delete curr; // <----added this instead of delPtr
	curr = prev->next;
	table[i] = curr; //<---added this
}
Last edited on
Topic archived. No new replies allowed.