Skip to content

Instantly share code, notes, and snippets.

@toanalien
Created June 5, 2015 19:15
Show Gist options
  • Save toanalien/6e3c32f8eae4d0f227d7 to your computer and use it in GitHub Desktop.
Save toanalien/6e3c32f8eae4d0f227d7 to your computer and use it in GitHub Desktop.
hash table
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <iostream>
using namespace std;
#define MAX 50
typedef struct SSTUDENT
{
char Name[30];
float Mark;
struct SSTUDENT *next;
} STUDENT, *PSTUDENT;
int HashFunc(char str[])
{
int i, n = strlen(str);
int m = 0;
for (i = 0; i < n; i++)
m = (m * 29 + (str[i] - 'A')) % MAX;
return m;
}
void Add(PSTUDENT HashTable[], STUDENT st)
{
int key = HashFunc(st.Name);
PSTUDENT p;
p = new STUDENT;
p->Mark = st.Mark;
strcpy(p->Name, st.Name);
p->next = NULL;
p->next = HashTable[key];
HashTable[key] = p;
}
PSTUDENT Search(PSTUDENT HashTable[], char Name[], PSTUDENT prev)
{
PSTUDENT p;
int key = HashFunc(Name);
prev = NULL;
p = HashTable[key];
while (p != NULL)
{
if (strcmp(p->Name, Name) == 0)
{
return p;
}
prev = p;
p = p->next;
}
return NULL;
}
void Del(PSTUDENT HashTable[], char Name[])
{
PSTUDENT p, prev;
p = Search(HashTable, Name, prev);
if (p != NULL)
if (prev != NULL)
prev->next = p->next;
else
HashTable[HashFunc(Name)] = p->next;
}
int main()
{
FILE *src_file;
PSTUDENT HashTable[MAX];
STUDENT st;
char s[15];
char *pChar;
int count = 0;
for (int i = 0; i <MAX; i++)
HashTable[i] = NULL;
src_file = fopen("DSSinhvien.txt", "r");
if (fgets(s,35,src_file)!=NULL)
count = atoi(s);
for (int i = 0; i < count;i++)
{
if (fgets(s, 35, src_file)!=NULL)
{
char tmp[30];
pChar = strstr(s, "***");
strncpy(tmp, s, strlen(s) - strlen(pChar));
tmp[strlen(s) - strlen(pChar)] = '\0';
strcpy(st.Name, tmp);
st.Mark = atoi(pChar + 3);
Add(HashTable, st);
}
}
//test add student
/*PSTUDENT prev=NULL;
PSTUDENT search_pstudent = Search(HashTable, "nguyen van a", prev);
printf("%s \t %f", search_pstudent->Name, search_pstudent->Mark);*/
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment