Created
February 1, 2016 09:03
-
-
Save avdyushin/673b1b5523cc3ad66669 to your computer and use it in GitHub Desktop.
Stack data structure via linked lists using Swift enums
This file contains hidden or 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 LinkedList<T> { | |
case Empty | |
case Node(value: T, next: LinkedList<T>) | |
init() { self = .Empty } | |
} | |
extension LinkedList { | |
func cons(x: T) -> LinkedList<T> { | |
return .Node(value: x, next: self) | |
} | |
} | |
extension LinkedList { | |
mutating func push(item: T) { | |
self = .Node(value: item, next: self) | |
} | |
mutating func pop() -> T? { | |
switch self { | |
case let .Node(value, next): | |
self = next | |
return value | |
case .Empty: | |
return nil | |
} | |
} | |
func peek() -> T? { | |
switch self { | |
case let .Node(value, _): | |
return value | |
case .Empty: | |
return nil | |
} | |
} | |
} | |
extension LinkedList: ArrayLiteralConvertible { | |
init(arrayLiteral elements: T...) { | |
self = elements.reverse().reduce(.Empty) { | |
$0.cons($1) | |
} | |
} | |
} | |
extension LinkedList: SequenceType { | |
func generate() -> AnyGenerator<T> { | |
var current = self | |
return anyGenerator { | |
switch current { | |
case let .Node(value, next): | |
current = next | |
return value | |
case .Empty: | |
return nil | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment