两个多项式相乘 使用散列表加速 在计算时合并多项式的项

数据结构与算法分析——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
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值