-
Notifications
You must be signed in to change notification settings - Fork 276
/
Stack.swift
95 lines (61 loc) · 1.52 KB
/
Stack.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// Stack.swift
// SwiftStructures
//
// Created by Wayne Bishop on 8/1/14.
// Copyright (c) 2014 Arbutus Software Inc. All rights reserved.
//
import Foundation
class Stack<T> {
private var top: Node<T>
private var counter: Int = 0
init() {
top = Node<T>()
}
//the number of items - O(1)
var count: Int {
return counter
}
//add item to the stack - O(1)
func push(withKey key: T) {
//return trivial case
guard top.key != nil else {
top.key = key
counter += 1
return
}
//create new item
let childToUse = Node<T>()
childToUse.key = key
//set new created item at top
childToUse.next = top
top = childToUse
//set counter
counter += 1
}
//remove item from the stack - O(1)
func pop() {
if self.count > 1 {
top = top.next!
//set counter
counter -= 1
}
else {
top.key = nil
counter = 0
}
}
//retrieve the top most item - O(1)
func peek() -> Node<T> {
return top
}
//check for value - O(1)
func isEmpty() -> Bool {
if self.count == 0 {
return true
}
else {
return false
}
}
}