【发布时间】:2017-05-15 10:18:11
【问题描述】:
我正在尝试使用单独的链接冲突解决方案来实现哈希表,但我遇到了问题。 这是我的代码(稍作修改以简化,但错误仍然相同):
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <fstream>
#include <cstring>
#include <string>
using namespace std;
int ascii(char character)
{
return character;
}
int hashFunction(string word, int num)
{
char* str = new char[word.length() + 1];
strcpy(str, word.c_str());
return ((3 * ascii(str[0]) + 5 * ascii(str[1]))) % num;
}
typedef struct tab
{
string data;
struct tab* next;
}Node;
typedef struct link
{
Node* head;
Node* tail;
}List;
List* createList()
{
List* list = new List();
if (list)
{
list->head = NULL;
list->tail = NULL;
}
return list;
}
void insert(List* list, string data)
{
//if list is empty
if (list->head == NULL) //!!!!!!!!!!!!!!!!ERROR OCCURE HERE !!!!!!!!!!!!!!!
{
list->head = new Node();
list->head->data = data;
list->head->next = NULL;
list->tail = list->head;
}
//if list already contains some data
else
{
list->tail->next = new Node();
list->tail->next->data = data;
list->tail = list->tail->next;
list->tail->next = NULL;
}
}
int main(int argc, char* argv[])
{
int size = 8; //Size of hash table (number of indexes)
List* table[12];
string A[8] = { "hello","world","car","notebook","science","starwars","lollypop","anything" };
//Insert elements from array A into a hash table
int index;
for (int i = 0; i < size; i++)
{
index = hashFunction(A[i], size);
if (table[index] == NULL)
table[index] = createList();
insert(table[index], A[i]);
}
return 0;
}
当我运行 .exe 文件(或从 cmd 启动)时,程序结束时显示 app.exe 已停止工作的消息。我尝试调试程序并得到了这个: http://imgur.com/a/yOhRV
谁能帮我解决这个问题?我发现问题一定出在 insert() 函数中,可能在条件中,但我不知道出了什么问题。
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用debugger 来单步执行您的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs.