Created
April 2, 2017 04:32
-
-
Save rayfix/398e2c92c1edf0e331ed39208129470f to your computer and use it in GitHub Desktop.
An alternate (slightly memory hungry) solution to the middle problem
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
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