【发布时间】: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