简单来讲这个题可以直接用STL里面的vector实现,这里我使用了数组+链表实现,略微有点麻烦,想了解更多关于哈希表的资料请点击这里
附上本题代码
#include <iostream>
#include <algorithm>
using namespace std ;
struct node
{
int key ;
node *next ;
};
node arr[13] ;
void insert(node arr[], int key , int position)
{
if (arr[position].next == NULL)
{
node *temp = new node();
temp -> key = key ;
temp -> next = NULL ;
arr[position].next = temp ;
}
else
{
node *p = arr[position].next ;
while (p->next)
{
p = p -> next ;
}
node *temp = new node();
temp -> key = key ;
temp -> next = NULL ;
p -> next = temp ;
}
}
void print(node arr[])
{
for (int i = 0 ; i < 13 ; i ++ )
{
node *p = arr[i].next ;
cout << i << '#' ;
if (p == NULL)
{
cout << "NULL" ;
}
else
{
while (p)
{
if (p -> next == NULL)
{
cout << p-> key ;
p = p -> next ;
}
else
{
cout << p -> key << " " ;
p = p -> next ;
}
}
}
cout << endl ;
}
}
int main()
{
int temp = 0 ;
cin >> temp ;
while (temp != 0)
{
for (int i = 0 ; i < temp ; i ++ )
{
int number_test = 0;
cin >> number_test ;
int position = number_test % 13 ;
insert(arr, number_test , position) ;
}
if (temp != 0)
{
print(arr) ;
}
//这里至关重要,一定要记得清空原来存的内容
for(int i = 0 ; i < 13 ; i++ )
{
arr[i].next = NULL ;
}
cin >> temp ;
}
}