【问题标题】:Hashing, linked list, delete node散列、链表、删除节点
【发布时间】:2014-04-11 13:54:14
【问题描述】:

我的任务是从指向结构的指针数组中删除一个节点。

我的代码不起作用,我只是不知道为什么:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Jmena4.h"

#define LENGTH 101
#define P 127
#define Q 31

typedef struct node {
    char *name;
    struct uzel *next;
} NODE;

int hash(const char Name[]) {
    int i;
    int n = strlen(Name);
    int result;

    result = Name[0] * P + Name[1] * Q + Name[n - 1] + n;
    return result % LENGTH;
}

void Insert(NODE *array[], const char *name) {
    NODE *u;
    int h;

    u = (NODE*)malloc(sizeof(NODE));
    u->name = name;
    h = hash(name);

    u->next = array[h];
    array[h] = u;
}

int Search(NODE *array[], const char *name) {
    NODE *u;

    u = array[hash(name)];

    while (u != NULL) {
        if (strcmp(u->name, name) == 0) {
            printf("%s\n", u->name);
            return 1;
        }
        u = u->next;
    }
    printf("Name: %s wasn't found\n", name);
    return 0;
}

int Delete(NODE *array[], const char *name) {
    NODE *current;
    NODE *previous;
    int position = hash(name);

    current = array[position];
    previous = NULL;

    while (current != NULL) {
        if (strcmp(current->name, name) == 0) {
            if (previous == NULL) {
                array[position] = current->next;
                return 1;
            } else {
                previous->next = current->next;
                current = NULL;
                return 1;
            }
        }
        previous = current;
        current = current->next;
    }
    return 0;
}



int main() {
    int i;
    NODE *array[LENGTH];

    for (i = 0; i < LENGTH; i++) {
        array[i] = NULL;
    }

    for (i = 0; i < Pocet; i++) {
        Insert(array, Jmena[i]);
    }

    for (i = 0; i < PocetZ; i++) {
        Delete(array, JmenaZ[i]);
    }

    Search(array, "Julie");

    system("PAUSE");
    return 0;
}

编辑 1:我更改了变量的名称,而不是 position = array[position] 应该是 current = array[position],但它仍然不起作用。

编辑 2:在数组 Jmena 中是字符串“Julie”,我可以在 Insert 函数后搜索它,但是在我从 JmenaZ 中删除不包含“Julie”的字符串后,程序输出为:名称:未找到 Julie。

【问题讨论】:

  • 请添加语言标签。另外,请多解释一下我们的代码。你是什​​么意思你的代码不起作用?给我们示例输入和输出。
  • 如果您尝试在每次删除后进行搜索(而不是全部删除);它会在它们中的任何一个之后起作用吗?

标签: c list linked-list


【解决方案1】:

一方面,currentwhile 循环中进行测试之前并未初始化。

【讨论】:

  • 我认为他的意思是current = array[position]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-03-31
  • 2015-04-15
  • 2019-05-10
  • 2021-07-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多