-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstack.cpp
129 lines (98 loc) · 2.98 KB
/
stack.cpp
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// Copyright (C) 2014 Ben Murrell
#include <iostream>
#include <sstream>
using std::cout;
using std::endl;
// LIFO Stack
class Stack {
public:
// Constructor
Stack( int aDefaultCapacity = 64 ) {
mCapacity = aDefaultCapacity;
mData = new int[mCapacity];
}
// Destructor
~Stack() {
// Release resources
delete[] mData;
}
// Push value to top of stack
void push( int aItem ) {
// Need to expand internal storage?
if( mTop >= mCapacity ) {
// Alloc 2x the current space
int newCapacity = mCapacity * 2;
int* newStorage = new int[newCapacity];
// Copy data into new memory
memcpy( newStorage, mData, mCapacity * sizeof( int ) );
// Free old data
delete[] mData;
// Use new memory
mData = newStorage;
mCapacity = newCapacity;
}
mData[mTop] = aItem;
mTop++;
}
// Pop value from top of stack
int pop() {
int value = 0;
// Only get value if stack is not empty
if( mTop >= 1 ) {
mTop--;
value = mData[mTop];
}
return value;
}
// Peek at value on top of stack
int peek() const {
int value = 0;
if( mTop >= 1 ) {
value = mData[mTop - 1];
}
return value;
}
// Get size of stack
int size() const {
return mTop;
}
// Get string contents for testing
std::string contents() const {
std::ostringstream sout;
for( int i = 0; i < mTop; i++ ) {
sout << mData[i] << ", ";
}
return sout.str();
}
private:
int mCapacity; // Capacity of stack
int* mData; // Container of stack
int mTop; // Top of stack (location of *next* item)
};
int main( int argc, char** argv ) {
Stack myStack(2);
// Test adding to empty stack
myStack.push( 1 );
cout << myStack.contents() << endl; // 1
// Test adding to non-empty stack
myStack.push( 2 );
cout << myStack.contents() << endl; // 1 2
// Test adding beyond current capacity
myStack.push( 3 );
cout << myStack.contents() << endl; // 1 2 3
myStack.push( 4 );
cout << myStack.contents() << endl; // 1 2 3 4
// Test size
cout << myStack.size() << endl; // 4
// Test peek
cout << myStack.peek() << endl; // 4
// Test popping from stack
cout << myStack.pop() << endl; // 4
cout << myStack.pop() << endl; // 3
cout << myStack.pop() << endl; // 2
cout << myStack.pop() << endl; // 1
cout << myStack.size() << endl; // 0
// Test popping from empty stack
cout << myStack.pop() << endl; // 0
return 0;
}