#include<stdio.h>
#include<stdlib.h>
#define PRIME 271
typedef struct linkedlistNode {
int index;
linkedlistNode *next;
}listNode;
typedef linkedlistNode *plinklist;
void HashTablefree(plinklist HashTable, int PrimeNumber)
{
int index=0;
for (index = 0; index < PrimeNumber; index++)
{
plinklist tail = HashTable[index].next;
while (tail != NULL)
{
plinklist tmp = tail;
tail = tail->next;
free(tmp);
}
}
free(HashTable);
}
int* Twosum_Hash(int number[], int n, int Target)
{
if ((number == NULL) | (n < 2))
{
return NULL;
}
int index = 0;
int PrimeNumber = PRIME;
plinklist Hashtable = (plinklist)malloc(sizeof(linkedlistNode)*PrimeNumber);
if (Hashtable == NULL)
{
printf("memory allocation for hashTable failed!\n");
return NULL;
}
for (index = 0; index < PrimeNumber; index++)
{
Hashtable[index].index = -1;
Hashtable[index].next = NULL;
}
//创建哈希表对应关系
for (index = 0; index < n; index++)
{
int bias = abs(number[index]%PrimeNumber);
if (Hashtable[bias].index == -1)
{ Hashtable[bias].index = index; }
else
{
plinklist tail = (plinklist)malloc(sizeof(linkedlistNode));
if (tail == NULL)
{
printf("memory allocation for tail failed!\n");
HashTablefree(Hashtable, PrimeNumber);
return NULL;
}
tail->next = Hashtable[bias].next;
tail->index = index;
Hashtable[bias].next = tail;
}
}
//搜索我们的数据,看是否存在。
int *ret = (int*)malloc(sizeof(int) * 2);
for (index = 0; index < n; index++)
{
int bias = abs((Target-number[index])%PrimeNumber);
if (Hashtable[bias].index == -1) continue;
if ((Hashtable[bias].index + number[index] == Target)& (Hashtable[bias].index != index))
{
ret[0] = index + 1;
ret[1] = Hashtable[bias].index + 1;
HashTablefree(Hashtable, PrimeNumber);
return ret;
}
else
{
plinklist tail = Hashtable[bias].next;
while (tail != NULL)
{
if (Hashtable[bias].index + number[index] == Target)
{
ret[0] = index + 1;
ret[1] = tail->index + 1;
HashTablefree(Hashtable, PrimeNumber);
return ret;
}
else
{
tail = tail->next;
}
}
}
}
HashTablefree(Hashtable, PrimeNumber);
return NULL;
}
int main(int argc,char **argv)
{
int array[] = { 3, 2, 4 };
size_t n = sizeof(array) / sizeof(int);
int target = 6;
int* result = Twosum_Hash(array, (int)n, target);
if (NULL != result)
{
printf("The index1: %d; the index2: %d\n", result[0], result[1]);
printf("values are %d and %d.", array[result[0] - 1], array[result[1] - 1]);
free(result);//memory deallocation
}
else
{
printf("result is not available!\n");
}
system("pause");
}
我这边没报错,只打印了result is not available! 那你的报错信息是什么?