Last active
March 18, 2017 13:56
-
-
Save cgoldsby/5c54bfff3a374e2f9cce8b44bdcf868f to your computer and use it in GitHub Desktop.
MiSwift Challenge #2 - Linked 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
//: Playground - noun: a place where people can play | |
import Foundation | |
class Node<T> { | |
let value: T | |
var next: Node<T>? | |
init(value: T) { | |
self.value = value | |
} | |
} | |
class LinkedList<T>: Sequence, CustomStringConvertible, ExpressibleByArrayLiteral { | |
private (set) var head: Node<T>? | |
private (set) var tail: Node<T>? | |
func append(_ value: T) { | |
let node = Node(value: value) | |
if let head = head { | |
head.next = node | |
} | |
else { | |
head = node | |
} | |
tail = node | |
} | |
// MARK: - ExpressibleByArrayLiteral | |
required init(arrayLiteral elements: T...) { | |
for element in elements { | |
append(element) | |
} | |
} | |
// MARK: - Sequence | |
func makeIterator() -> AnyIterator<T> { | |
var node = head | |
return AnyIterator { | |
defer { node = node?.next } | |
return node?.value | |
} | |
} | |
// MARK: CustomStringConvertible | |
var description: String { | |
return map { $0 }.description | |
} | |
} | |
let linkedList = LinkedList<Int>() // [] | |
linkedList.append(1) // [1] | |
linkedList.append(2) // [1, 2] | |
let emojis: LinkedList = ["π", "π"] | |
emojis.head?.value // "π" | |
emojis.tail?.value // "π" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment