在插入中,我试图插入一对,一个键和另一个称为值。 我一直试图让我的插入功能工作,看起来像这样 我输入的错误一直在被调用,说一个密钥已经存在,但事实并非如此。
void insert(Dictionary D, char* key, char* value){
Node N;
if(lookup(D,key)!= NULL){
fprintf(stderr, "Dictionary Error: calling insert() on a key that already exists %s\n ", key);
exit(EXIT_FAILURE);
}else{
if(D-> == NULL){//if the list is empty
N = newNode(key);
N->next = D->head;
D->head = N;
D->tail = N;
D->head->next = newNode(value);
}else{
D->tail->next=newNode(key);
D->tail= newNode(key);
D->tail = newNode(value);
D->tail = newNode(value);
}
}
D->numItems++;
D->numItems++;
}
我的查找和findKey函数如下所示:
//lookup()
//returns the value v such that k, v is in D, or returns NULL if no
//value v exists
char* lookup(Dictionary D, char* key){
if(findKey(D, key)==NULL){
return NULL;
}else{
Node N = findKey(D, key);
return N;//changed this at lookup, when I write to string make sure that this works
}
}
//findKey()
//returns a reference to hte node at position of the key in the dictionary
Node findKey(Dictionary D, char* key){
Node N = NULL;
N = D->head;
while(N != NULL){
if(strcmp(N->item, key)==0){
N = N->next;
}
return N;
}
return N;
}
答案 0 :(得分:1)
在findKey
函数中,你根本不会循环,你将无条件地在循环的第一次迭代中返回。
我认为你的意思是这样做。
Node findKey(Dictionary D, char* key){
Node N = NULL;
N = D->head;
while(N != NULL){
if(strcmp(N->item, key)==0){
return N;
}
N = N->next;
}
return N;
}
请注意,我换了两行:内部return
语句和N = N->next;
语句。