在插入中,我试图插入一对,一个键和另一个称为值。我一直在尝试让我的插入函数工作,看起来像这样我输入的错误一直被调用,说一个键已经存在,但它不存在。
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 %sn ", 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;
}
在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;
语句。