分离链接法的删除操作函数_散列表

裁判测试程序样例:

1 #include <stdio.h>
2 #include <string.h>
3
4 #define KEYLENGTH 15 /* 关键词字符串的最大长度 */
5 typedef char ElementType[KEYLENGTH+1]; /* 关键词类型用字符串 */
6 typedef int Index; /* 散列地址类型 */
7 typedef enum {false, true} bool;
8
9 typedef struct LNode *PtrToLNode;
10 struct LNode {
11 ElementType Data;
12 PtrToLNode Next;
13 };
14 typedef PtrToLNode Position;
15 typedef PtrToLNode List;
16
17 typedef struct TblNode *HashTable; /* 散列表类型 */
18 struct TblNode { /* 散列表结点定义 */
19 int TableSize; /* 表的最大长度 */
20 List Heads; /* 指向链表头结点的数组 */
21 };
22
23 Index Hash( ElementType Key, int TableSize )
24 {
25 return (Key[0]-'a')%TableSize;
26 }
27
28 HashTable BuildTable(); /* 裁判实现,细节不表 */
29 bool Delete( HashTable H, ElementType Key );
30
31 int main()
32 {
33 HashTable H;
34 ElementType Key;
35
36 H = BuildTable();
37 scanf("%s", Key);
38 if (Delete(H, Key) == false)
39 printf("ERROR: %s is not found\n", Key);
40 if (Delete(H, Key) == true)
41 printf("Are you kidding me?\n");
42 return 0;
43 }
44
45 /* 你的代码将被嵌在这里 */

分离链接法的删除操作函数_散列表_02

 

1 bool Delete( HashTable H, ElementType Key )
2 {
3 int HashPos = Hash(Key, H->TableSize);
4 PtrToLNode p = H->Heads[HashPos].Next;
5
6 /* 链表为空 */
7 if(p == NULL)
8 return false;
9
10 /* 删除第一个元素 */
11 if(!strcmp(p->Data, Key))
12 {
13 H->Heads[HashPos].Next = p->Next;
14 p->Next = NULL;
15 free(p);
16 printf("%s is deleted from list Heads[%d]", Key, HashPos);
17 return true;
18 }
19
20 /* 删除非第一个元素 */
21 PtrToLNode q = p;
22 p = p->Next;
23 while(p)
24 {
25 if(!strcmp(p->Data, Key))
26 {
27 q->Next = p->Next;
28 p->Next = NULL;
29 free(p);
30
31 printf("%s is deleted from list Heads[%d]", Key, HashPos);
32 return true;
33 }
34 q = p;
35 p = p->Next;
36 }
37 /* 没找到 */
38 return false;
39 }