Last active
March 3, 2017 03:25
-
-
Save sgr-ksmt/c3ecca550353ff66a2d40ffe429c2668 to your computer and use it in GitHub Desktop.
LinkedList in Swift
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 { | |
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