【发布时间】:2016-03-02 03:21:01
【问题描述】:
我正在我的代码中处理删除功能。我想删除节点内的key, value 对并释放分配给它的空间。我不知道如何解决这个问题,以便以下节点转移到正确的位置(不知道如何措辞,希望你知道我的意思)。这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include "symTable.h"
#define DEFAULT_TABLE_SIZE 61
#define HASH_MULTIPLIER 65599
/*Structures*/
typedef struct Node
{
char *key;
void *value;
struct Node *next;
} Node_T;
typedef struct SymTable
{
Node_T **Table;
int tablesize;
int counter;
} *SymTable_T;
/*Global Variables*/
int tablesize = DEFAULT_TABLE_SIZE;
int counter = 0;
/*Create function to show how memory is allocated*/
SymTable_T SymTable_create(void)
{
SymTable_T S_Table;
S_Table = malloc(sizeof(SymTable_T *) * DEFAULT_TABLE_SIZE);
S_Table->Table = (Node_T **) calloc(DEFAULT_TABLE_SIZE, sizeof(Node_T *));
return S_Table;
}
/*Hash Function*/
static unsigned int hash(const char *key, const int tablesize)
{
int i;
unsigned int h = 0U;
for (i = 0; key[i] != '\0'; i++)
h = h * tablesize + (unsigned char) key[i];
return h % tablesize;
}
/*Delete Function*/
int symTable_delete(SymTable_T symTable, const char *key)
{
Node_T *new_list;
unsigned int hashval = hash(key, DEFAULT_TABLE_SIZE);
free(new_list->key);
free(new_list->value);
//here is where I am stuck, how can I make it so the nodes following the one deleted go to the right space?
}
【问题讨论】:
-
就像提到的@pwilmot。从表的顶部开始并对其进行迭代,直到下一个节点具有键。你要删除的那个。把那个复制出来。将下一个节点指向关键节点的下一个节点。然后释放关键节点内存。
-
要查找下一个节点是否持有该密钥,是否类似于
if (strcmp(key, new_list->next->key) == 0)?我不确定如何指向下一个节点的键。
标签: c linked-list hashtable nodes