cannot go thought linked list in hash function

line 28 does not work, i cannot go thought the linked list to the NULL and create new data

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
  static int const size = 10;

struct Item{
	string name;
	Item* link;
};

Item* b[size];

int prehash(string name){
	int n = 0;
	for (int i = 0; i < name.size(); i++)n += (int)name[i];
	n %= size;
	return n;
}

Item*getnew(string name){
	Item*temp = new Item;
	temp->name = name;
	temp->link = NULL;
	return temp;
}

void hashing(string name){
	int pos = prehash(name);
	if (b[pos] == NULL)b[pos] = getnew(name);
	else{
		while (b[pos] != NULL)b[pos] = b[pos]->link;
		b[pos] = getnew(name);
	}
}
Look at line 28 and imagine that b[pos] points to a list of 10 items when you get there. The first time through the loop, the code points b[pos] to the SECOND item, effectively throwing away the first time. The next time through it throws away the next item. By the time the loop ends, all 10 items have been thrown away.

What I think you should do is add the item to the beginning of the list instead of the end, It's much easier that way:
1
2
3
4
5
6
void hashing(string name){
	Item *tmp = getnew(name);
	int pos = prehash(name);
	tmp->link = b[pos];
	b[pos] = tmp;
}


BTW, rather than having getnew(), it would be better to make a constructor and use it:
1
2
3
4
5
6
7
8
9
10
11
12
Item(const string &str) :
		name(str), link(nullptr) {}
	string name;
	Item* link;
};

void hashing(string name){
	Item *tmp = new Item(name);
	int pos = prehash(name);
	tmp->link = b[pos];
	b[pos] = tmp;
}

Last edited on
thanks a lot
Topic archived. No new replies allowed.