数据结构与算法分析——c语言描述 练习5.7 答案
使用散列表加速,O(1)时间找到相同的指数多项式进行合并,原来是一遍又一遍扫表链表找到相同指数的合并,复杂度为O(M^2*N^2),现在为O(MN),由于散列表并不能比较大小之类的。所以要相乘后再遍历一遍散列表添加到链表(此时指数顺序是乱的)。没有排序。
头文件管理好麻烦,没有c++的命名空间,所以hash的position和list的position冲突的,解决办法就是起一个不同的名字。。。
还有elementType重定义,解决办法是新建一个头文件,把elementType的定义加上去。然后再在hash和list中include
ElementType.h
#pragma once
#ifndef _ElementType_H
#define _ElementType_H
struct ElementType {
int Coefficient;//系数
int Exponent;//指数
};
#endif // ! ElementType_H
hashQuad.h
#ifndef _HashQuad_H
#define _HashQuad_H
#include"ElementType.h"
typedef unsigned int Index;
typedef Index Position_hash;
struct HashTbl;
typedef struct HashTbl* HashTable;
HashTable initializeTable(int tableSize);
void destroyTable(HashTable h);
Position_hash find(ElementType key, HashTable h);
HashTable insert(ElementType key, HashTable h);
HashTable rehash(HashTable h);
ElementType retrive(Position_hash p, HashTable h);
int isLegitimate(Position_hash pos, HashTable h);
#endif
hashQuad.cpp
#include"hashQuad.h"
#include"fatal.h"
#include<math.h>
#include<string.h>
#define MinTableSize 5
enum KindOfEntry { Legitimate, Empty, Deleted };
struct HashEntry {
ElementType element;
enum KindOfEntry info;
};
typedef struct HashEntry Cell;
struct HashTbl {
int tableSize;
int hasInsertedNum;
Cell *theCells;//数组
};
static int hash(ElementType key, int tableSize) {
return key.Exponent % (tableSize);
}
static Position_hash hash2(ElementType key, int tableSize) {
return 7 - (key.Exponent % 7);
}
static int isPrime(int num) {
for (int i = 2; i <= sqrt(num); i++)
if (num%i == 0)
return 0;
return 1;
}
static int nextPrime(int num) {
int i = num;
while (!isPrime(i))
i++;
return i;
}
int isLegitimate(Position_hash pos, HashTable h) {
return h->theCells[pos].info == Legitimate;
}
HashTable initializeTable(int tableSize) {
HashTable h;
int i;
if (tableSize < MinTableSize) {
Error("Table size too smal