今天用分离链接法实现散列表时,本以为好好的代码莫名报错:unknown signal
。
ListNodePtr newNode = (ListNodePtr)malloc(sizeof(struct ListNode));
(ListNodePtr
是自定义的链表节点类型)
这种赋值语句也会报错吗?申请内存确实可能会出错,所以我加了个判断:
while (!newNode)
newNode = (ListNodePtr)malloc(sizeof(struct ListNode));
但是并没有用。还是在上一句赋值代码报错了,根本就没走到那句判断代码。
网上搜了一下,发现出现unknown signal
的错误代码都是跟内存有关,于是我检查了一下创建散列表的代码,发现自己忘记给链表数组加长度了。
错误代码:
hashTable->heads = (List)malloc(sizeof(struct ListNode));
乘上一个长度后确实就没问题了:
hashTable->heads = (List)malloc(sizeof(struct ListNode) * hashTable->tableSize);
以下是完整代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#define MAX_TABLE_SIZE 1000
typedef struct ListNode {
int key;
struct ListNode* next;
}*ListNodePtr;
typedef ListNodePtr List;
typedef struct TableNode {
List heads;
int tableSize;
}*HashTable;
int nextPrime(int num) {
int i, p = (num & 1) ? num + 2 : num + 1;
while (p <= MAX_TABLE_SIZE) {
for (i = (int)sqrt(p);i > 2;i--)
if (p % i == 0)
break;
if (i == 2)
break;
else
p += 2;
}
return p;
}
HashTable createHashTable(int tableSize) {
HashTable hashTable = (HashTable)malloc(sizeof(struct TableNode));
hashTable->tableSize = nextPrime(tableSize);
hashTable->heads = (List)malloc(sizeof(struct ListNode) * hashTable->tableSize);
for (int i = 0;i < hashTable->tableSize;i++) {
hashTable->heads[i].key = -1;
hashTable->heads[i].next = NULL;
}
return hashTable;
}
int hash(int key) {
return key % 11;
}
ListNodePtr find(HashTable hashTale, int key) {
int position = hash(key);
ListNodePtr p = hashTale->heads[position].next;
while (p && p->key != key)
p = p->next;
return p;
}
void Insert(HashTable hashTable, int key) {
ListNodePtr p = find(hashTable, key);
if (!p) {
ListNodePtr newNode = (ListNodePtr)malloc(sizeof(struct ListNode));
while (!newNode)
newNode = (ListNodePtr)malloc(sizeof(struct ListNode));
newNode->key = key;
int position = hash(key);
newNode->next = hashTable->heads[position].next;
hashTable->heads[position].next = newNode;
}
}
int getSearchTimes(HashTable hashTable, int key) {
int position = hash(key);
ListNodePtr p = hashTable->heads[position].next;
int searchTimes = 1;
while (p && p->key != key) {
searchTimes++;
p = p->next;
}
return searchTimes;
}
int main() {
int key;
int keyCount;
double totalSearchTimes = 0;
printf("请输入关键字数量:\n");
scanf("%d", &keyCount);
HashTable hashTable = createHashTable(keyCount);
int keyWords[keyCount];
printf("请输入关键字\n");
for (int i = 0;i < keyCount;i++) {
scanf("%d", &key);
Insert(hashTable, key);
keyWords[i] = key;
}
for (int i = 0;i < keyCount;i++)
totalSearchTimes += getSearchTimes(hashTable, keyWords[i]);
printf("散列表构建成功!\n成功查找的平均查找长度为:");
printf("%.2lf\n", totalSearchTimes / keyCount);
system("pause");
return 0;
}