Created
May 23, 2017 10:33
-
-
Save yoxisem544/862db244df852bd45370df4f89370a3e to your computer and use it in GitHub Desktop.
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
indirect enum LinkedListNode<T> { | |
case value(element: T, next: LinkedListNode<T>) | |
case end | |
} | |
extension LinkedListNode : Sequence { | |
typealias Iterator = LinkedListIterator<T> | |
func makeIterator() -> LinkedListIterator<T> { | |
return LinkedListIterator(current: self) | |
} | |
} | |
struct LinkedListIterator<T> : IteratorProtocol { | |
var current: LinkedListNode<T> | |
mutating func next() -> T? { | |
switch current { | |
case let .value(element: e, next: next): | |
current = next | |
return e | |
case .end: | |
return nil | |
} | |
} | |
} | |
extension LinkedListNode : ExpressibleByArrayLiteral { | |
typealias Element = T | |
init(arrayLiteral elements: Element...) { | |
// construct a linked list from its end. | |
// more efficient. | |
self = elements.reversed().reduce(LinkedListNode.end) { (currentNode, nextValue) -> LinkedListNode<Element> in | |
return LinkedListNode.value(element: nextValue, next: currentNode) | |
} | |
} | |
} | |
let list: LinkedListNode<String> = ["๐","๐","๐","๐","๐"] | |
list.forEach({ print($0) }) | |
list.contains("") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment