-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.cpp
More file actions
63 lines (49 loc) · 872 Bytes
/
stack.cpp
File metadata and controls
63 lines (49 loc) · 872 Bytes
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
#include <vector>
#include <string>
#include <iostream>
class cstack
// there is an STL stack, but we'll use this one for the exercise
{
private:
std::vector<char> data;
public:
cstack() = default;
void insert(char c)
// insert
{
data.push_back(c);
}
void pop()
// pop
{
data.pop_back();
}
char read()
// read
{
return data.back();
}
bool empty()
// check if stack is empty
{
return data.empty();
}
};
std::string reverseString(std::string s)
// reverse a string using our stack implementation
{
cstack stack = cstack();
std::string result;
for (auto c : s) {
stack.insert(c);
}
while (!stack.empty()) {
result += stack.read();
stack.pop();
}
return result;
}
int main(int argc, char** argv) {
std::string reversed = reverseString("reversed");
std::cout << reversed << std::endl;
}