Documente Academic
Documente Profesional
Documente Cultură
1)We hash each key : home address =key % hashsize , then we insert the key at the home address.
If other keys exist, the key is inserted at the start of the list
0 26 13
1
2 15 2
3 16 3
4
5 18 5
6
Optional:
Overloading %:
int operator%(string s,int hashsize)
{
int h=0;
for (int i=0;i<s.length();i++)h=h*2+s[i];
return h%hashsize;
}
This means that we will give the operator % a new meaning only when it has operands of the specified
types (left operand is string, right is int)
To call this function:
int h=s%hashsize;
Note that this doesn't affect the original meaning of % when given two integers (5%4 will still give 1)
4) Linear probing.
Remember that we insert nodes in the table at the home address. A collision means that 2 keys will
have the same home address. If collision occurs we will start at the home address and look for the next free
slot after it.
Note that in this implementation, a variable called slotStatus is associated with each slot.
It determines whether the slot is empty, in use or deleted.
Assume that a key (k1) has home address of 5. If the slot 5 is empty, k1 will be inserted at slot number 5.
If another key (k2) to be inserted has the same home address 5 (collision), it will try to find the first
slot that is not in use starting from 5, assume 6 is empty it will be inserted at 6.
Now assume that the first key (k1) is deleted. And we want to look for k2. We will start searching at its
home address 5. If we don't have the slot status to tell us that a key was deleted from slot 5, we will
assume that k2 doesn't exist. However knowing that a key was deleted from slot 5, we start looking in
the following slots, until we either find k2, or find a slot whose status is empty, so we conclude that the
key doesn't exist.
struct Slot
{
tableKeyType key;
tableDataType data;
};
Slot s; bool b;
b=T[pos].first(s);
while(b)
{
if(s.key==key)
{T[pos].deleteCurrent();return;}
b=T[pos].next(s);
}
}
// deleteCurrent() is a member function that we will add to the linked list class that will delete the node to
which 'current' points.
#include<assert.h>
template <class ListElementType>
class List
{
public:
List();
void insert(const ListElementType & elem);
bool first(ListElementType & elem);
bool next(ListElementType & elem);
private:
struct Node;
typedef Node *Link;
struct Node
{
ListElementType elem;
Link next;
};
Link head;
Link tail;
Link current;
};