Created
August 26, 2019 06:42
-
-
Save davidinga/212c3b8c2244e7ae1c4ba2e0ecb49fc3 to your computer and use it in GitHub Desktop.
Graph data structure in Swift using an Adjacency List.
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
public struct GraphAL<Element: Hashable> { | |
var adjList = [Element: GraphNode<Element>]() | |
public mutating func addVertex(_ name: Element) { | |
adjList[name] = GraphNode(name) | |
} | |
@discardableResult public mutating func addEdge(from source: Element, to destination: Element) -> Bool { | |
guard adjList[source] != nil, adjList[destination] != nil | |
else { return false } | |
var node = GraphNode(destination) | |
node.next = adjList[source] | |
adjList[source] = node | |
node = GraphNode(source) | |
node.next = adjList[destination] | |
adjList[destination] = node | |
return true | |
} | |
} |
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
public class GraphNode<Element: Hashable> { | |
public var data: Element | |
public var next: GraphNode<Element>? | |
init(_ element: Element) { | |
self.data = element | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment