Created
October 14, 2016 17:03
-
-
Save khanlou/b89eacffbc5455215046467510d1028a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 LinkedList<T> { | |
| var head: Node<T> | |
| init(head: Node<T>) { | |
| self.head = head | |
| } | |
| } | |
| indirect enum Node<T> { | |
| case value(element: T, next: Node<T>) | |
| case end | |
| } | |
| struct LinkedListIterator<T>: IteratorProtocol { | |
| var current: Node<T> | |
| mutating func next() -> T? { | |
| switch current { | |
| case let .value(element, nextNode): | |
| current = nextNode | |
| return element | |
| case .end: | |
| return nil | |
| } | |
| } | |
| } | |
| extension LinkedList: Sequence { | |
| func makeIterator() -> LinkedListIterator<T> { | |
| return LinkedListIterator(current: head) | |
| } | |
| } | |
| extension LinkedList: ExpressibleByArrayLiteral { | |
| init(arrayLiteral elements: T...) { | |
| var current = Node<T>.end | |
| for element in elements.reversed() { | |
| current = Node.value(element: element, next: current) | |
| } | |
| self.head = current | |
| } | |
| } | |
| let list = LinkedList<Int>(head: Node.value(element: 1, next: Node.value(element: 2, next: Node.end))) | |
| let arrayedList: LinkedList<Int> = [1, 2, 3] | |
| for element in arrayedList { | |
| print(element) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment