哈希表的基本运算(链表实现)

// 哈希表的基本运算.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"

typedef int KeyType;

const int NUM = 10;//0-9下表的数组用来存放不同索引值

#include

struct  HashTable

{

   KeyType key;

   HashTable *next;

   HashTable *head;//头结点

};

 

void Initial(KeyType a[],int n)//初始化数据

{

   cout<<"请输入"<<n<<"个测试数据"<<endl;

   for (int i = 0; i < n; i++)

   {

      cin>>a[i];

   }

}

 

void CreateHT(HashTable ht[],KeyType a[],int n)//采用头插法建立哈希表

{

   for (int i = 0; i < NUM; i++)

   {

      ht[i].head = new HashTable;

      ht[i].head->next = NULL;//初始化数据

   }

   for (int i = 0; i < n; i++)//采用带有头结点的头插法

   {

      int n = a[i] % NUM;

      //HashTable *head = new HashTable;

      HashTable * p = new HashTable;

      p->key = a[i];

      p->next = ht[n].head->next;

      ht[n].head->next = p;

      //ht[n].head = head;

   }

}

 

void display(HashTable ht[])//输出信息

{

   for (int i = 0; i < NUM; i++)

   {

      cout<<"索引为"<<i<<"的数据有:";

       HashTable *p = ht[i].head->next;

       while (p != NULL)

      {

        cout<<p->key<<"  ";

        p = p->next;

      }

   cout<<endl;

   }

}

 

void add(HashTable ht[],KeyType data)//插入数据

{

   int n = data % NUM;

   HashTable * p = new HashTable;

   p->key = data;

   p->next = ht[n].head->next;

   ht[n].head->next = p;

}

 

int Remove(HashTable ht[],KeyType data)

{

   int n = data % NUM;

   HashTable *p = ht[n].head;

   while (p != NULL)

   {

      HashTable *q = p;//q用来保存待删点的前一个点

      p = p->next;

      if(p->key == data)

      {

        if(p->next == NULL)//如果是所在索引表的最后一个元素

        {

           q->next = NULL;

        }

        else

        {

           q->next = p->next;

        }

        delete(p);

        return 1;//删除成功

      }

   }

   return 0;//删除失败

}

 

int _tmain(int argc, _TCHAR* argv[])

{

   HashTable ht[NUM];

   HashTable Test[NUM];

   int n;

   KeyType a[20];//假设数组长度不超过20

   cout<<"请输入测试数组的个数(这里假设小于20:"<<endl;

   cin>>n;

   Initial(a,n);

   CreateHT(ht,a,n);

   cout<<"插入数据前,数据为:"<<endl;

   display(ht);

   add(ht,5);

   cout<<"插入数据5之后,数据为:"<<endl;

   display(ht);

   cout<<"删除数据5之后,数据为:"<<endl;

   Remove(ht,5);

   display(ht);

   return 0;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值