Skip to content

Instantly share code, notes, and snippets.

@davidinga
Created August 26, 2019 06:42
Show Gist options
  • Save davidinga/212c3b8c2244e7ae1c4ba2e0ecb49fc3 to your computer and use it in GitHub Desktop.
Save davidinga/212c3b8c2244e7ae1c4ba2e0ecb49fc3 to your computer and use it in GitHub Desktop.
Graph data structure in Swift using an Adjacency List.
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
}
}
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