Hash表的创建与查找(用链表解决冲突)

Code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define KEYLENGTH 15                   /* 关键词字符串的最大长度 */
typedef char ElementType[KEYLENGTH+1]; /* 关键词类型用字符串 */
typedef int Index;                     /* 散列地址类型 */


typedef struct LNode *PtrToLNode;
struct LNode {
    ElementType Data;
    PtrToLNode Next;
};
typedef PtrToLNode Position;
typedef PtrToLNode List;


typedef struct TblNode *HashTable; /* 散列表类型 */
struct TblNode {   /* 散列表结点定义 */
    int TableSize; /* 表的最大长度 */
    List Heads;    /* 指向链表头结点的数组 */
};


Index Hash( ElementType Key, int TableSize )
{
    return (Key[0]-'a')%TableSize;
}


HashTable BuildTable()
{
    HashTable H;
    H = (TblNode*) malloc(sizeof(TblNode));


    int n;
    scanf("%d", &n);
    H->TableSize = n;
    H->Heads = (LNode*) malloc(sizeof(LNode) * n);
    char key[20];
    for(int i = 0; i < n; i++)
        H->Heads[i].Next = NULL;
    for(int i = 0; i < n; i++)
    {
        bool flag = false;
        scanf("%s", key);
        int x = Hash(key, n);
        PtrToLNode ptr = &(H->Heads[x]);
        PtrToLNode cur = H->Heads[x].Next;
        PtrToLNode p;
        p = (LNode*) malloc(sizeof(LNode));
        p->Next = NULL, strcpy(p->Data, key);
        while(cur != NULL)
        {
            if(strcmp(cur->Data, key) == 0)
                {flag = true; break;}
            ptr = cur, cur = cur->Next;
        }
        if(flag == false)
            ptr->Next = p;
    }
    return H;
}


bool Delete( HashTable H, ElementType Key )
{
    int i = Hash(Key, H->TableSize);
    PtrToLNode cur = (H->Heads[i]).Next;
    PtrToLNode ptr = &(H->Heads[i]);
    while(cur != NULL && strcmp(cur->Data, Key) != 0)
        ptr = cur, cur = cur->Next;
    if(cur == NULL)
        return false;
    else
    {
        ptr->Next = cur->Next;
        printf("%s is deleted from list Heads[%d]\n",Key, i);
        return true;
    }
}




int main()
{
    HashTable H;
    ElementType Key;


    H = BuildTable();
    scanf("%s", Key);
    if (Delete(H, Key) == false)
        printf("ERROR: %s is not found\n", Key);
    if (Delete(H, Key) == true)
        printf("Are you kidding me?\n");
    return 0;
}


/*
6
zero
able
key
very
bye
day
*/

阅读更多
换一批

没有更多推荐了,返回首页