Untitled

 avatar
unknown
plain_text
2 years ago
1.6 kB
5
Indexable
#include <iostream>
#include "ConsoleApplication1.h"
using namespace std;
#define M 100

struct NODE {
    int key;
    NODE* pNext;
};
// Khai báo kiểu con trỏ chỉ node
typedef NODE* NODEPTR;
typedef NODEPTR HASHTABLE[M];

NODE* CreateNode(int x) {
    NODE* p;
    p = new NODE;
    p->key = x;
    p->pNext = NULL;
    return p;
}
void AddTail(NODE*& head, int x) {
    NODE* p = CreateNode(x);
    if (head == NULL) head = p;
    else {
        NODE* i = head;
        while (i->pNext != NULL) {
            i = i->pNext;
        }
        i->pNext = p;
    }
}

int HF(int numbucket, int key)
{
    return key % numbucket;
}

void InitHASHTABLE(HASHTABLE& H,int numbucket) {
    for (int i = 0; i < numbucket; i++)
    {
        H[i] = NULL;
    }

}
void traverseHASHTABLE(HASHTABLE& H,int i) {
    NODEPTR p = H[i];
    while (p != NULL) {
        std::cout << " --> ";
        cout << p->key;
        p = p->pNext;
    }
}
void Traverse(HASHTABLE& H, int numbucket) {
    for (int i = 0; i < numbucket; i++) {
        cout << endl << i;
        traverseHASHTABLE(H,i);
    }
}

void CreateHashTable(HASHTABLE& H, int numbucket )
{
    cin >> numbucket;
    int index;
    InitHASHTABLE(H, numbucket);
    cin >> index;
    int KEY;
    while (index != -1)
    {
        KEY = HF(numbucket,index);
        AddTail(H[KEY], index);
        cin >> index;
    }
    return;
}


int main() {
    HASHTABLE H;
    int numbucket;

    CreateHashTable(H, numbucket);
    Traverse(H, numbucket);

    return 0;
}
Editor is loading...