散列,链表,删除节点

时间:2014-04-11 13:54:15

标签: c list linked-list

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

我的代码不起作用,我只是不知道原因:

#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”,我可以在插入函数后搜索它,但是在我从JmenaZ中删除不包含“Julie”程序输出的字符串后:名称:找不到Julie。

1 个答案:

答案 0 :(得分:2)

首先,currentwhile循环中进行测试之前未初始化。