forked from JuezUN/opt-cpp-backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcpp-stackarray.cpp
More file actions
125 lines (94 loc) · 2.21 KB
/
Copy pathcpp-stackarray.cpp
File metadata and controls
125 lines (94 loc) · 2.21 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
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
// From the test suite of https://github.com/codespecs/daikon
// daikon/tests/kvasir-tests/
#include <iostream>
#include <stdlib.h>
#include <string.h>
using namespace std;
class Stack {
public:
Stack(char* name, int maxSize);
~Stack();
void push(int dat);
int peek();
int pop();
char* getName();
int getMaxElts();
int getNumElts();
static int getNumStacksCreated();
private:
int numElts;
int maxElts;
char* myName;
int* stackRep;
static int numStacksCreated;
int privateStuff();
};
int Stack::numStacksCreated;
Stack::Stack(char* name, int maxSize) {
myName = strdup(name);
maxElts = maxSize;
numElts = 0;
Stack::numStacksCreated++;
stackRep = new int[maxSize];
}
void Stack::push(int dat) {
if (numElts < maxElts) {
numElts++;
stackRep[numElts - 1] = dat;
}
}
int Stack::peek() {
if (numElts > 0)
return stackRep[numElts - 1];
else
return 0; // Yeah, I know, no error handling :)
}
int Stack::pop() {
if (numElts > 0) {
privateStuff();
numElts--;
return stackRep[numElts];
}
else
return 0; // Yeah, I know, no error handling :)
}
char* Stack::getName() {return myName;}
int Stack::getMaxElts() {return maxElts;}
int Stack::getNumElts() {return numElts;}
int Stack::getNumStacksCreated() {
return Stack::numStacksCreated;
}
Stack::~Stack() {
delete[] stackRep;
free(myName);
}
int Stack::privateStuff() {
cout << "\n!PRIVATE!";
return 42;
}
int main() {
Stack first((char*)"My first stack", 10);
first.push(101);
first.push(102);
first.push(103);
first.push(104);
first.push(105);
// Pop the lines from the Stack and print them:
cout << first.getName() << ": MAX_ELTS: " << first.getMaxElts();
cout << ", NUM_STACKS_CREATED: " << first.getNumStacksCreated() << endl;
int s;
while((s = first.pop()) != 0) {
cout << s << endl;
}
Stack second((char*)"My second stack", 5);
second.push(1001);
second.push(1002);
second.push(1003);
cout << second.getName() << ": MAX_ELTS: " << second.getMaxElts();
cout << ", NUM_STACKS_CREATED: " << first.getNumStacksCreated() << endl;
// Pop the lines from the Stack and print them:
while((s = second.pop()) != 0) {
cout << s << endl;
}
return 0;
}