Skip to content

Instantly share code, notes, and snippets.

@rayfix
Created April 2, 2017 04:32
Show Gist options
  • Save rayfix/398e2c92c1edf0e331ed39208129470f to your computer and use it in GitHub Desktop.
Save rayfix/398e2c92c1edf0e331ed39208129470f to your computer and use it in GitHub Desktop.
An alternate (slightly memory hungry) solution to the middle problem
public enum LinkedList<T> {
case end
indirect case node(value: T, next: LinkedList)
public func cons(_ value: T) -> LinkedList {
return .node(value: value, next: self)
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
switch self {
case .end:
return "end"
case let .node(value, next):
return "\(value) -> " + next.description
}
}
}
extension Array {
var middle: Element? {
return count > 0 ? self[count/2] : nil
}
}
extension LinkedList: Sequence {
public func makeIterator() -> AnyIterator<T> {
var current = self
return AnyIterator<T> {
switch current {
case let .node(value, next):
current = next
return value
case .end:
return nil
}
}
}
}
extension LinkedList {
func middle() -> T? {
return Array(self).middle
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment