Created
February 26, 2016 14:55
-
-
Save Que20/e77e6195b8737bcf5b3b to your computer and use it in GitHub Desktop.
Swift Data Structures
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
// 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