-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdynamic-stack.cpp
More file actions
81 lines (65 loc) · 1.61 KB
/
dynamic-stack.cpp
File metadata and controls
81 lines (65 loc) · 1.61 KB
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
#include "dynamic-stack.h"
#include <iostream>
const DynamicStack::StackItem DynamicStack::EMPTY_STACK = -999;
DynamicStack::DynamicStack() {
capacity_ = 16;
init_capacity_ = 16;
size_ = 0;
items_ = new int [capacity_];
}
DynamicStack::DynamicStack(unsigned int capacity){
capacity_ = init_capacity_ = capacity;
size_ = 0;
items_ = new int [capacity_];
}
DynamicStack::~DynamicStack() {
delete [] items_;
items_ = nullptr;
}
unsigned int DynamicStack::size() const {
return size_;
}
bool DynamicStack::empty() const {
return size_ == 0;
}
DynamicStack::StackItem DynamicStack::peek() const {
if(empty())
return EMPTY_STACK;
else
return items_[size_-1];
}
void DynamicStack::push(StackItem value) {
if(size_ == capacity_) {
int *newItems = new int[2 * capacity_];
capacity_ = 2 * capacity_;
for (int i = 0; i < size_; i++) {
newItems[i] = items_[i];
}
int *temp = items_;
items_ = newItems;
delete[] temp;
temp = nullptr;
}
items_[size_] = value;
size_++;
}
DynamicStack::StackItem DynamicStack::pop() {
if (empty())
return EMPTY_STACK;
StackItem top = items_[size_-1];
size_--;
if (size_ <= capacity_ / 4) {
StackItem *newItems = new int [capacity_ / 2];
for (int i = 0; i < size_; i++) {
newItems[i] = items_[i];
}
delete[]items_;
items_ = newItems;
}
return top;
}
void DynamicStack::print() const {
for (int i = 0; i < size_; i++) {
std::cout << items_[i] << ", ";
}
}