Skip to content

Instantly share code, notes, and snippets.

@fitomad
Created May 17, 2018 21:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fitomad/c259c31fc1b3e75ef31d555d95e3d673 to your computer and use it in GitHub Desktop.
Save fitomad/c259c31fc1b3e75ef31d555d95e3d673 to your computer and use it in GitHub Desktop.
Swift Stack Data Structure
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