Skip to content

Instantly share code, notes, and snippets.

@sgr-ksmt
Last active March 3, 2017 03:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgr-ksmt/c3ecca550353ff66a2d40ffe429c2668 to your computer and use it in GitHub Desktop.
Save sgr-ksmt/c3ecca550353ff66a2d40ffe429c2668 to your computer and use it in GitHub Desktop.
LinkedList in Swift
indirect enum LinkedListNode<T> {
case value(element: T, next: LinkedListNode<T>)
case end
}
extension LinkedListNode: Sequence {
func makeIterator() -> LinkedListIterator<T> {
return LinkedListIterator(self)
}
}
struct LinkedListIterator<T>: IteratorProtocol {
var current: LinkedListNode<T>
init(_ current: LinkedListNode<T>) {
self.current = current
}
mutating func next() -> T? {
switch current {
case .value(let element , let next):
self.current = next
return element
case .end:
return nil
}
}
}
// =============
let list = LinkedListNode.value(element: 10, next: .value(element: 20, next: .value(element: 30, next: .end)))
list.forEach { number in
print(number)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment