Core JavaScript

A Hash Table with Linked Lists

This JavaScript Reference section displays the code for an example program that shows how to create a hash table with linked list entries in JavaScript.

HashTableWithLinkedLists.html

<!DOCTYPE html>
<html>
	<head>
		<title>XoaX.net's Javascript</title>
		<script type="text/javascript" src="HashTableWithLinkedLists.js"></script>
	</head>
	<body onload="Execute()">
	</body>
</html>

HashTableWithLinkedLists.js

function Execute() {
	let qHashTable = new CHashTable();
	for (let iEntry = 0; iEntry < 35; ++iEntry) {
		let sNewValue = "";
		let iNewKey = 0;
		let qNewKeyValue = null
		for (let i = 0; i < 10; ++i) {
			// This is an ASCII or unicode character code value
			let iCharCode = 97 + Math.floor(Math.random()*(123 - 97));
			// The key will be the sum of the character codes
			iNewKey += iCharCode;
			// Convert the code to a character and append it to the string value
			sNewValue += String.fromCodePoint(iCharCode);
			qNewKeyValue = new CKeyValue(iNewKey, sNewValue);
		}
		qHashTable.Insert(qNewKeyValue);
	}
	qHashTable.Print();
}

class CKeyValue {
	miKey;
	mqValue; // The values are strings of randomly generated characters
	constructor(iKey, qValue) {
		this.miKey = iKey;
		this.mqValue = qValue;
	}
	toString() {
		return " <i>"+this.miKey+"</i>, <b>\""+this.mqValue+"\"</b> ";
	}
}

class CHashTable {
	mqaData = null;
	constructor() {
		this.mqaData = new Array(15);
		for (let i = 0; i < this.mqaData.length; ++i) {
			this.mqaData[i] = new CLinkedList();
		}
	}
	Insert(qKeyValue) {
		let qNewLink = new CLink(qKeyValue);
		let iHash = (qNewLink.mqData.miKey % this.mqaData.length);
		this.mqaData[iHash].InsertAtHead(qNewLink)
	}
	Print() {
		for (let i = 0; i < this.mqaData.length; ++i) {
			this.mqaData[i].Print();
		}
	}
}


class CLink {
	mqData;
	mqNext = null;
	constructor(qData) {
		this.mqData = qData;
	}
	toString() {
		return "[" +this.mqData.toString() + "]&#x2192;";
	}
}

class CLinkedList {
	mqpHead = null;
	constructor() {}
	InsertAtHead(qNewLink) {
		qNewLink.mqNext = this.mqpHead;
		this.mqpHead = qNewLink;
	}
	Print() {
		let qNewDiv = document.createElement("div");
		let qpCurr = this.mqpHead;
		while (qpCurr != null) {
			qNewDiv.innerHTML += qpCurr.toString();
			qpCurr = qpCurr.mqNext;
		}
		qNewDiv.innerHTML += "null";
		let qBody = document.body;
		qBody.appendChild(qNewDiv);
	}
}

 

Output

 
 

© 2007–2026 XoaX.net LLC. All rights reserved.