Skip to content

Instantly share code, notes, and snippets.

@Que20
Created February 26, 2016 14:55
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 Que20/e77e6195b8737bcf5b3b to your computer and use it in GitHub Desktop.
Save Que20/e77e6195b8737bcf5b3b to your computer and use it in GitHub Desktop.
Swift Data Structures
// Stack
struct Stack<T> {
var items = [T]()
mutating func push(item: T) {
items.append(item)
}
mutating func pop() -> T {
return items.removeLast()
}
}
var stackStrings = Stack<String>()
stackInts.push("Hello")
stackInts.push("World")
stackInts.push("Swift")
stackInts.push("Stack")
print("pop: \(stackStrings.pop())")
// Tree
class TreeNode<T: Comparable> {
var val: T?
var leftNode: TreeNode?
var rightNode: TreeNode?
//add item based on its value
func addNode(val: T) {
if (self.val == nil) {
self.val = val
print("Added Head")
return
}
if (val < self.val) {
if let left = self.leftNode {
left.addNode(val)
} else {
let newLeft = TreeNode()
newLeft.val = val
self.leftNode = newLeft
print("Added Left")
}
}
if (val > self.val) {
if let right = self.rightNode {
right.addNode(val)
} else {
let newRight = TreeNode()
newRight.val = val
self.rightNode = newRight
print("Added Right")
}
}
}
}
let numbers: Array<Int> = [8, 3, 5, 2, 7, 9, 13, 16, 10, 22]
var root = TreeNode<Int>()
for n in numbers {
print(n)
root.addNode(n)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment