gpt4 book ai didi

c - C 中的映射数组 - 带键 : Value 的链表

转载 作者:行者123 更新时间:2023-11-30 17:41:01 25 4
gpt4 key购买 nike

好吧,我的问题是,当我写入节点时,它只会覆盖头节点,因此当您调用 map_get 时,您只能获得一个包含数据的节点。我想将数据放在头上,或者推送头节点并将其卡在前面,这两种方法都可以,无论哪种方法最简单,最好感谢您的帮助。

#include <assert.h>
#include<stdlib.h>
#include "map.h"
#include <string.h>
int main(){
map_t* newList = malloc(sizeof(map_t));
map_init(newList);
const char* passString ="a";
const char* secondString="2";
map_put(newList,"3","3");
map_put(newList,"7","34");
map_put(newList,"a","45");
map_put(newList,passString,secondString);
map_get(newList,secondString);
}

void map_init(map_t* self) {
map_entry_t* newNode= malloc(sizeof(map_entry_t)); // allocate
self->size = 0;
self->entry = newNode; // link next
}

int map_put(map_t* self, const char* key, const char* val) {
assert(self != NULL);
map_entry_t* current;
//current = self->entry->key;
while(current->next != NULL){
current = current->next;

}
self->entry->key = key;
self->entry->value = val;
map_entry_t* newNode = malloc(sizeof(map_entry_t));


printf("\ntry printing the list \n");
printf(self->entry->key);
printf(" :was the key and the value is \n");
printf(self->entry->value);
printf("\n");


}

const char* map_get(map_t* self, const char* key) {
assert(self != NULL);
const char* target = key;
int i=0;
for(i; i<=self->size; i++)
{
printf("\n\ninside the list\n");
printf(self->entry->value);
printf("\n");
}
}

int map_size(map_t* self) {
assert(self != NULL);

}

int map_remove(map_t* self, const char* key) {
assert(self != NULL);

}

int map_serialize(map_t* self, FILE* stream) {
assert(self != NULL);

}

int map_deserialize(map_t* self, FILE* stream) {
assert(self != NULL);

}

void map_destroy(map_t* self) {
assert(self != NULL);

}


map.h

#ifndef __A1_MAP_H__
#define __A1_MAP_H__

#include <stdio.h>

#define SYS_ERROR -1
#define OK 0
#define KEY_EXISTS 1
#define NO_KEY_EXISTS 2

// Strange type definition due to the recursive nature
// of the struct. This technique is called 'forward
// declaration' and is necessary for compilation reasons.
typedef struct _map_entry map_entry_t;
struct _map_entry {
char* key;
char* value;
map_entry_t* next;
} ;

typedef struct _map {
map_entry_t* entry;
int size;
} map_t;

// Part one functions.
void map_init(map_t*);
int map_put(map_t*, const char*, const char*);
const char* map_get(map_t*, const char*);
int map_remove(map_t*, const char*);
int map_size(map_t*);
void map_destroy(map_t*);

// Part two functions.
int map_serialize(map_t*, FILE*);
int map_deserialize(map_t*, FILE*);

#endif

最佳答案

map_put中,您应该初始化current以指向列表的头部self。现在,它开始指向内存中的某个地方,然后您尝试从那里开始遍历列表。然后,您完全忽略它并直接写入列表的头元素 (self),而不是新节点 (newNode)。然后,您还需要设置从当前节点到新节点的链接。

关于c - C 中的映射数组 - 带键 : Value 的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21287547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com