

解题思路:采用散列表(链表)存储账号密码的信息
#include <stdio.h>
#include <math.h>
#include <malloc.h>
#include <string.h>
typedef enum {false,true
} bool;
typedef struct LNode {
char num[11];
char pw[17];
struct LNode *Next;
}*List,LNode;
typedef struct {
int TableSize;
List *HashList;
}*HashTable;
bool IsPrime(int n) {
if(n==0||n==1)
return false;
if(n>2) {
int i;
for(i=2; i<=sqrt(n)+1; i++) {
if(n%i==0)return false;
}
}
return true;
}
int NextPrime(int n) {
int i=n+1;
while(!IsPrime(i))
i++;
return i;
}
HashTable Create(int size) {//初始化散列表
HashTable H=(HashTable)malloc(sizeof(HashTable));
H->TableSize=NextPrime(size);
H->HashList=(List*)malloc(sizeof(List)*H->TableSize);
int i;
for(i=0; i<H->TableSize; i++) {
H->HashList[i]=(List)malloc(sizeof(List));
H->HashList[i]->Next=NULL;
}
return H;
}
int hash(HashTable H,char *s) {//用号码后4位mod表长作为关键字地址
int keylength=strlen(s);
return atoi(s+keylength-4)%H->TableSize;
}
LNode* IsExist(HashTable H,char *s,int key) {//判断号码是否存在,返回插入位置
LNode *p=H->HashList[key];
while(p->Next) {
if(strcmp(p->Next->num,s)==0) {
break;
}
p=p->Next;
}
return p;
}
int main() {
int size;
scanf("%d",&size);
int i;
char c,num[11]="",pwd[17]="";
HashTable H=Create(size);
for(i=0; i<size; i++) {
getchar();
scanf("%c %s%s",&c,num,pwd);
int key=hash(H,num);
LNode *p=IsExist(H,num,key);
if(c=='N') {
if(!p->Next) {
LNode *node=(LNode *)malloc(sizeof(LNode));
node->Next=NULL;
strcpy(node->num,num);
strcpy(node->pw,pwd);
p->Next=node;
p=node;
printf("New: OK
");
} else
printf("ERROR: Exist
");
} else if(c=='L') {
if(p->Next) {
if(strcmp(p->Next->pw,pwd)==0)
printf("Login: OK
");
else
printf("ERROR: Wrong PW
");
} else
printf("ERROR: Not Exist
");
}
}
return 0;
}