Study/Data Structure

[Data Structure] HashTable C++로 만들기

wnwnovo 2024. 10. 10. 08:45
// Hash.cpp : This file contains the 'main' function. Program execution begins and ends there.
//

#include <iostream>
#include <list>
#define HASH_TABLE_COUNT 11

class HashTable
{
    public:
    struct stData
    {
        int ID;
        int value;

        stData* next;
        stData()
        {
            ID = 0;
            value = 0;
            next = NULL;
        }
    };
    stData* hashList[HASH_TABLE_COUNT];
    int GetHashKey(int ID)
    {
        return ID % HASH_TABLE_COUNT;
    }

    void AddValue(int ID, int value)
    {
        stData* data = new stData;
        data->ID = ID;
        data->value = value;
        int index = GetHashKey(ID);
        stData* listData = hashList[index];
        if (hashList[index] != NULL)
        {
            data->next = listData;
            hashList[index] = data;
        }
        else
        {
            hashList[index] = data;
        }
    }

    void RemoveValue(int ID)
    {
        int index = GetHashKey(ID);
        stData* data = hashList[index];
        stData* tempData = data;
        while (data)
        {
            if (data->ID == ID)
            {
                if (hashList[index] == data)
                {
                    hashList[index] = data->next;
                }
                else
                {
                    tempData->next = data->next;
                }
                printf("제거된 ID : %d , Value : %d\n", ID, data->value);
                break;
            }
            tempData = data;
            data = data->next;
        }
    }

    void DisplayHash()
    {
        printf("\n");
        int i = 0;
        for (int i = 0; i < HASH_TABLE_COUNT; ++i)
        {
            stData* data = hashList[i];
            int size = 0;
            printf("값: ");
            while (data)
            {
                if (data->next != NULL)
                {
                    printf("%d, ", data->value);
                }
                else
                {
                    printf("%d      ", data->value);
                }
                data = data->next;
                ++size;
            }
            printf("\n[%d] 개수 : %d\n\n", i, size);
        }
        printf("\n");
    }
};


int main()
{
    HashTable* hash = new HashTable;
    memset(hash->hashList, 0, sizeof(hash->hashList));

    for (int i = 1; i < 100; ++i)
    {
        int val = rand();
        hash->AddValue(i, val);
    }

    printf("[Add End]\n");
    // 값 출력
    hash->DisplayHash();

    int ids[] = { 3,12,21,37,41,56,67,43,28,97 };
    for (int i = 0; i < 10; ++i)
    {
        hash->RemoveValue(ids[i]);
    }
    printf("[Remove End]\n");
    // 값 출력
    hash->DisplayHash();
    delete(hash);
}

'Study > Data Structure' 카테고리의 다른 글

[Data Structure] Tree C++로 만들기  (0) 2024.10.10
[Data Structure] List C++로 만들기  (0) 2024.10.10