Skip to content

Instantly share code, notes, and snippets.

@deda9
Created July 11, 2019 15:22
Show Gist options
  • Save deda9/4090ab5cdd32ad507293dfbe069ec0df to your computer and use it in GitHub Desktop.
Save deda9/4090ab5cdd32ad507293dfbe069ec0df to your computer and use it in GitHub Desktop.
How to create LinkedList with enum
indirect enum LinkedList<T> {
case value(element: T, next: LinkedList<T>)
case end
}
extension LinkedList: Sequence {
func makeIterator() -> LinkedListIterator<T> {
return LinkedListIterator(current: self)
}
}
struct LinkedListIterator<T>: IteratorProtocol {
var current: LinkedList<T>
mutating func next() -> T? {
switch current {
case . value(let element, let next):
self.current = next
return element
case .end:
return nil
}
}
}
let x3: LinkedList<Int> = .end
let x2: LinkedList<Int> = .value(element: 3, next: x3)
let x1: LinkedList<Int> = .value(element: 32, next: x2)
let x: LinkedList<Int> = .value(element: 23, next: x1)
x.forEach {
print($0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment