Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 26, 2019 21:54
Show Gist options
  • Save davidinga/c27385cfd717f9b53082c5d252cc1277 to your computer and use it in GitHub Desktop.
Save davidinga/c27385cfd717f9b53082c5d252cc1277 to your computer and use it in GitHub Desktop.
Simple Hash Table implementation in Swift. Includes Linked List, and Node structures. Basic methods.
struct HashTable<Key: Hashable, Value> {
private typealias Element = (key: Key, value: Value)
private typealias List = LinkedList<Element>
private var table: [List]
init(size: Int) {
table = Array<List>()
for _ in 0..<size {
let list = List()
table += [list]
}
}
func value(forKey key: Key) -> Value? {
let index = self.index(forKey: key)
var node = table[index].head
while node != nil {
if node!.data.key == key {
return node!.data.value
}
node = node!.next
}
return nil
}
mutating func append(_ value: Value, forKey key: Key) {
let index = self.index(forKey: key)
table[index].append((key: key, value: value))
}
func index(forKey key: Key) -> Int {
return abs(key.hashValue % table.count)
}
}
class LinkedList<Element> {
var head: Node<Element>?
var tail: Node<Element>?
func append(_ element: Element) {
let node = Node(element)
if tail != nil {
tail!.next = node
} else {
head = node
}
tail = node
}
}
class Node<Element> {
var data: Element
var next: Node<Element>?
init(_ data: Element) {
self.data = data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment