Skip to content

Instantly share code, notes, and snippets.

@khanlou
Created October 14, 2016 17:03
Show Gist options
  • Select an option

  • Save khanlou/b89eacffbc5455215046467510d1028a to your computer and use it in GitHub Desktop.

Select an option

Save khanlou/b89eacffbc5455215046467510d1028a to your computer and use it in GitHub Desktop.
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