筆試題:再hash法


#include<iostream>
#include <string.h>
#define DefaultSize 13
using namespace std;

struct PeopleNode
{
    int flags;
    char *name;
    PeopleNode():flags(0),name(new char[20]){}
};

class Hash
{
public:
    Hash(int n = DefaultSize)
    {
        pnode = new PeopleNode[n];
    }
    int hash(char ch)
    {
        return ch%DefaultSize;
    }
    void Insert(char *_name)
    {
        char *p = _name;
        while (*p != '\0')
        {
            int index = hash(*p);
            if (pnode[index].flags == 0)
            {
                strcpy(pnode[index].name,_name);
                pnode[index].flags = 1;
                return;
            }
            p++;
        }
        for (int i = 0; i < DefaultSize; ++i)
        {
            if (pnode[i].flags == 0)
            {
                strcpy(pnode[i].name,_name);
                pnode[i].flags = 1;
                return;
            }
        }
        cout << "Error  ,There is full!" << endl;
        return;
    }
    void Printf()
    {
        for (int i = 0; i < DefaultSize; ++i)
        {
            if (pnode[i].flags == 1)
                cout << pnode[i].name << endl;
        }
    }
private:
    PeopleNode *pnode;
};
int main()
{
    Hash sh;
    sh.Insert("liuhuiyan");
    sh.Insert("liuhhh");
    sh.Insert("li");
    sh.Printf();
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章