和上一篇的题没有什么区别,只是多了一些过程控制
另外尽管题目中说明了对密码格式的要求,但实际上题目并没有给出相应的正确输出格式示例,测试用例中也没有测试点。所以也就没写这部分函数


下面是题解,哈希函数依旧使用了针对性能优秀的DJB2算法

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#define MAX 100003

//哈希表结点结构体
typedef struct Account{
    char user_account[11];
    char user_pin[17];
    struct Account* next;
}Account;

//哈希表
Account *hashTable[MAX] = {NULL};

//哈希函数
unsigned long getHash(const char *account){
    unsigned long hash_value = 5381;
    int c;
    while((c = *(account++))){
        hash_value = (hash_value*33)+c;
    }
    return hash_value%MAX;
}


//核心函数,查找或者插入
int getCommand(char command,char *account ,char *pin){
    unsigned long hash_value = getHash(account);
    //无论是什么命令都要对输入的账号进行查找
    Account* current = hashTable[hash_value];
    while(current != NULL){
        if(strcmp(current->user_account,account)==0){
            //找到账号
            if(command == 'N'){
                //命令为申请新账号,但账号已经存在,故返回错误码1
                return 1;
            }else if(command == 'L'){
                //用户请求登录
                if(strcmp(current->user_pin,pin) == 0){
                    //密码校验通过,返回状态码2
                    return 2;
                }else{
                    //密码校验未通过,返回错误码3
                    return 3;
                }
            }
        }
        current = current->next;
    }
    //未找到目标账号
    if(command == 'N'){
        //可以创建新账号,创建在链表的头部位置
        Account* newAccount = (Account*)malloc(sizeof(Account));
        strcpy(newAccount->user_account,account);
        strcpy(newAccount->user_pin,pin);
        newAccount->next = hashTable[hash_value];
        hashTable[hash_value] = newAccount;
        //创建完毕返回状态码4
        return 4;
    }else if(command == 'L'){
        //未找到目标账号,返回错误码5
        return 5;
    }
}


int main(){
    int N;
    scanf("%d",&N);
    getchar();
    char command,account[11],pin[17];
    for(int i = 0; i < N; i++){
        scanf(" %c %s %s",&command,account,pin);
        int status = getCommand(command,account,pin);
        switch(command){
        case 'N':
            if(status == 1){
                printf("ERROR: Exist\n");
                break;
            }else if(status == 4){
                printf("New: OK\n");
                break;
            }
        case'L':
            if(status == 2){
                printf("Login: OK\n");
                break;
            }else if(status == 3){
                printf("ERROR: Wrong PW\n");
                break;
            }else if(status == 5){
                printf("ERROR: Not Exist\n");
                break;
            }
        }
    }
    return 0;
}

更多推荐