Untitled

mail@pastecode.io avatar
unknown
plain_text
2 years ago
1.8 kB
1
Indexable
Never
#include<iostream>
using namespace std;
#include<list>

/* Cau truc Hash Table */
struct Hash {
	int slot;
	// Pointer to an array containing slots
	list<int>* table;
};
/* Ham Khoi Tao Hash Table */
void create_Hash(Hash& h, int b);
/* Ham Hashing */
int hash_func(Hash h, int x);
/* Them Item vao HTable */
void insertItem(Hash& h, int key);
/* Xoa 1 Item */
void deleteItem(Hash& h, int key);
// Display hash table 
void display_hash(Hash h);

void create_Hash(Hash& h, int b)
{
	h.slot = b;
	h.table = new list<int>[b];
}

int hash_func(Hash h, int x)
{
	return x % (h.slot);
}

void insertItem(Hash& h, int key)
{
	int nkey = hash_func(h, key);
	h.table[nkey].push_back(key);
}

void deleteItem(Hash& h, int key)
{
	int nkey = hash_func(h, key);
	int flag = 0;
	list <int> ::iterator i;
	for (i = h.table[nkey].begin(); i != h.table[nkey].end(); i++)
	{
		if (h.table[nkey].empty() == false)
		{
			if (*i == key)
			{
				h.table[nkey].remove(key);
				flag = 1;
			}
		}


	}
	if (flag == 0)
	{
		cout << key << " khong ton tai ";
	}
}

void display_hash(Hash h)
{
	for (int i = 0; i < h.slot; i++)
	{
		cout << i;
		if (h.table[i].size() != 0)
		{
			list <int> ::iterator j;
			for (j = h.table[i].begin(); j != h.table[i].end(); j++)
			{
				cout << "-->" << *j;
			}
			cout << endl;
		}
		
	}
}

int main()
{
	Hash h;
	int n;
	cout << "Nhap so hang cua bang bam: ";
	cin >> n;
	create_Hash(h, n);
	int x;
	do
	{
		cout << "Nhap phan tu vao bang: ";
		cin >> x;
		if (x < 0)
			break;
		else
			insertItem(h, x);

	} while (x > 0);
	cout << "Bang bam ban dau: " << endl;
	display_hash(h);
	int k;
	cout << "Nhap phan tu can xoa: ";
	cin >> k;
	deleteItem(h, k);
	display_hash(h);
}