Skip to content

Commit ef7a338

Browse files
Added Stack playground
1 parent 219fc85 commit ef7a338

File tree

3 files changed

+67
-0
lines changed

3 files changed

+67
-0
lines changed

Stack/Stack.playground/Contents.swift

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/*
2+
3+
Stack
4+
5+
A stack is like an array but with limited functionality. You can only push to add a new element to the top of the stack, pop to remove the element from the top, and peek at the top element without popping it off.
6+
7+
A stack gives you a LIFO or last-in first-out order. The element you pushed last is the first one to come off with the next pop. (A very similar data structure, the queue, is FIFO or first-in first-out.)
8+
9+
Insertion - O(1)
10+
Deletion - O(1)
11+
12+
13+
*/
14+
15+
import UIKit
16+
17+
public struct Stack<T> {
18+
private var array = [T]()
19+
20+
public var count: Int {
21+
return array.count
22+
}
23+
24+
public var isEmpty: Bool {
25+
return array.isEmpty
26+
}
27+
28+
public mutating func push(element: T) {
29+
array.append(element)
30+
}
31+
32+
public mutating func pop() -> T? {
33+
if count == 0 {
34+
return nil
35+
} else {
36+
return array.removeLast()
37+
}
38+
}
39+
40+
public func peek() -> T? {
41+
return array.last
42+
}
43+
44+
}
45+
46+
47+
var stackOfNames = Stack(array: ["Carl", "Lisa", "Stephanie", "Jeff", "Wade"]) // Initialized queue
48+
49+
stackOfNames.push("Mike") // Adds element to the end of the stack. Stack is now ["Carl", "Lisa", "Stephanie", "Jeff", "Wade", "Mike"]
50+
51+
stackOfNames.pop() // Removes and returns the last element in the stack. Returns "Mike" and then removes it from the stack
52+
53+
stackOfNames.peek() // Returns the first element in the stack. Returns "Wade" since "Mike" was popped on the previous line
54+
55+
stackOfNames.isEmpty // Checks to see if the stack is empty. Returns "False" since the stack still has elements in it
56+
57+
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
2+
<playground version='5.0' target-platform='ios'>
3+
<timeline fileName='timeline.xctimeline'/>
4+
</playground>
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<?xml version="1.0" encoding="UTF-8"?>
2+
<Timeline
3+
version = "3.0">
4+
<TimelineItems>
5+
</TimelineItems>
6+
</Timeline>

0 commit comments

Comments
 (0)