Created
August 26, 2019 21:54
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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