请给出一个可以运行的C语言代码,选择合适的散列函数和冲突处理方法,编程实现QQ账户申请与登录
时间: 2023-11-22 11:51:48 浏览: 30
以下是一个简单的哈希表实现,使用链式哈希表解决哈希冲突的问题。其中,散列函数采用了除留余数法,但可以根据实际需求进行修改。
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ACCOUNTS 1000
#define HASH_SIZE 100
typedef struct account_t {
char username[20];
char password[20];
} Account;
typedef struct node_t {
Account data;
struct node_t* next;
} Node;
Node* hash_table[HASH_SIZE];
unsigned int hash(const char* str) {
unsigned int hash = 0;
while (*str) {
hash = (hash * 31 + *str) % HASH_SIZE;
str++;
}
return hash;
}
void insert_account(Account new_account) {
unsigned int index = hash(new_account.username);
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->data = new_account;
new_node->next = hash_table[index];
hash_table[index] = new_node;
}
Account* find_account(const char* username) {
unsigned int index = hash(username);
Node* curr = hash_table[index];
while (curr) {
if (strcmp(curr->data.username, username) == 0) {
return &(curr->data);
}
curr = curr->next;
}
return NULL;
}
int main() {
int choice;
Account new_account;
while (1) {
printf("1. Register\n2. Login\n3. Exit\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter username: ");
scanf("%s", new_account.username);
printf("Enter password: ");
scanf("%s", new_account.password);
insert_account(new_account);
printf("Account registered successfully.\n");
break;
case 2:
printf("Enter username: ");
scanf("%s", new_account.username);
printf("Enter password: ");
scanf("%s", new_account.password);
Account* found = find_account(new_account.username);
if (found && strcmp(found->password, new_account.password) == 0) {
printf("Login successful.\n");
} else {
printf("Invalid username/password.\n");
}
break;
case 3:
exit(0);
default:
printf("Invalid choice.\n");
}
}
return 0;
}
```