Created
May 17, 2018 21:14
-
-
Save fitomad/c259c31fc1b3e75ef31d555d95e3d673 to your computer and use it in GitHub Desktop.
Swift Stack Data Structure
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
import Foundation | |
public struct Stack<Element> | |
{ | |
private var storage: [Element] | |
public init() | |
{ | |
self.storage = [Element]() | |
} | |
public mutating func push(_ element: Element) -> Void | |
{ | |
self.storage.insert(element, at: 0) | |
} | |
public mutating func pop() -> Element? | |
{ | |
return self.storage.removeFirst() | |
} | |
public func whosOnTop() -> Element? | |
{ | |
return self.storage.first | |
} | |
} | |
// | |
// TEST | |
// | |
var stack = Stack<Int>() | |
stack.push(1) | |
stack.push(2) | |
stack.push(3) | |
stack.push(4) | |
stack.push(5) | |
if let top = stack.whosOnTop() | |
{ | |
print("Top \(top)") | |
} | |
print(stack) | |
if let fuera = stack.pop() | |
{ | |
print("Fuera: \(fuera)") | |
} | |
print(stack) | |
stack.push(5) | |
print(stack) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment