2014-04-11 59 views
0

我的任務是從指向結構的指針數組中刪除一個節點。散列,鏈表,刪除節點

我的代碼不工作,我只是不知道爲什麼:

#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」的字符串後,程序輸出爲:Name:Julie未找到。

+3

請添加語言標籤。另外,請更多地解釋我們的代碼。你的意思是你的代碼不起作用?給我們樣本輸入和輸出。 –

+0

如果您在每次刪除後嘗試搜索(而不是全部),該怎麼辦?它們之後會起作用嗎? –

回答

2

首先,currentwhile循環中進行測試之前未初始化。

+0

我認爲他的意思是'current = array [position]' – GoldRoger