C中的映射数组 - 使用/ Key:Value的链接列表

时间:2014-01-22 15:48:36

标签: c map linked-list associative-array

好吧我的问题是当我编写节点时它只是覆盖头节点,因此当你调用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

1 个答案:

答案 0 :(得分:0)

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