【7050】已知散列函数为H(key)=key mod 13,冲突处理方法为外拉链法实现散列表的建立(利用插入算法实现)

【7050】已知散列函数为H(key)=key mod 13,冲突处理方法为外拉链法实现散列表的建立(利用插入算法实现)_第1张图片

#include
using namespace std;

typedef struct node {

    node* next;
	int data;

}LNode, * LinkList;

typedef struct hashlist {

	int ListLength;
	LinkList list;

}HashList;

void List_Insert_HashList(HashList l, int key) {
	//calculate p value
	int p = 0;
	for (int i = l.ListLength; i > 0; i--) {
		int flag = 0;
		for (int j = i - 1; j > 1; j--) {
			if (i % j == 0) {
				flag = 1;
			}
		}
		if (flag == 0) {
			p = i;
			break;
		}
	}

	int h = key % p;

	if (l.list[h].data == 0) {
		l.list[h].data = key;
	}
	else {
		LinkList p = new LNode;
		p->data = l.list[h].data;
		p->next = l.list[h].next;
		l.list[h].data = key;
		l.list[h].next = p;
	}

}

int main() {
	
	int m = 13;
	
	//create and initial hashlist
	HashList l;
	l.ListLength = m;
	l.list = new LNode[m];
	for (int i = 0; i < m; i++) {
		l.list[i].data = 0;
		l.list[i].next = NULL;
	}
	
	int key;
	cin >> key;
	while (key != 0) {
		List_Insert_HashList(l, key);
		cin >> key;
	}

	for (int i = 0; i < m; i++) {
		cout << i << ":";
		if (l.list[i].data != 0) {
			cout << l.list[i].data << " ";
		}
		LinkList p = l.list[i].next;
		while (p != NULL) {
			cout << p->data << " ";
			p = p->next;
		}
		cout << "\n";
	}

	return 0;
}

你可能感兴趣的:(代码模板)