【问题标题】:C - Deleting a node in a linked listC - 删除链表中的节点
【发布时间】: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-&gt;next-&gt;key) == 0)?我不确定如何指向下一个节点的键。

标签: c linked-list hashtable nodes


【解决方案1】:

有了单链表,你就有了

A -> B -> C

如果你想删除 B 那么你需要做

A -> C

这样做的唯一方法是获取 B 的父级并更新其指针,这意味着要么

  1. 您需要添加一个从节点到其父节点的指针(也就是使用双向链表)
  2. 您遍历列表,直到找到一个节点,其中子指针设置为您要删除的节点,然后您将指针更新为指向 child.child

【讨论】:

    猜你喜欢
    • 2016-01-02
    • 1970-01-01
    • 2019-05-10
    • 2021-07-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-21
    • 2013-08-30
    • 2019-05-10
    相关资源
    最近更新 更多