Skip to content

Commit 8e446af

Browse files
committed
Add Datastructure: Stack
1 parent 97ec67b commit 8e446af

File tree

2 files changed

+114
-0
lines changed

2 files changed

+114
-0
lines changed

DataStructure/Stack/example.cpp

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
/*
2+
* example.cpp
3+
* Copyright (C) 2019 Guowei Chen <[email protected]>
4+
*
5+
* Distributed under terms of the MIT license.
6+
*/
7+
8+
9+
#include <iostream>
10+
#include "stack.hpp"
11+
12+
int main()
13+
{
14+
stack stk;
15+
stk.push(1);
16+
stk.push(2);
17+
18+
std::cout << "After push 1, 2, then stk.top() => " << stk.top() << "\n";
19+
20+
stk.pop();
21+
std::cout << "After push 1, 2, pop, then stk.top() => " << stk.top() << "\n";
22+
stk.pop();
23+
24+
stk.push(3);
25+
std::cout << "After push 1, 2, pop, pop, push 3, then stk.top() => ";
26+
std::cout << stk.top() << "\n";
27+
28+
return 0;
29+
}

DataStructure/Stack/stack.hpp

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/*
2+
* stack.hpp
3+
* Copyright (C) 2019 Guowei Chen <[email protected]>
4+
*
5+
* Distributed under terms of the MIT license.
6+
*/
7+
8+
#ifndef _STACK_HPP_
9+
#define _STACK_HPP_
10+
11+
#include <cstdlib>
12+
13+
static constexpr int M = 10;
14+
15+
class stack {
16+
public:
17+
stack();
18+
stack(int size);
19+
~stack();
20+
21+
void push(int n);
22+
int pop();
23+
int top();
24+
25+
private:
26+
int * _arr = nullptr;
27+
int _top = -1;
28+
int _capacity = 0;
29+
30+
bool isFull();
31+
bool isEmpty();
32+
};
33+
34+
bool stack::isFull() {
35+
return _top >= _capacity - 1;
36+
}
37+
38+
bool stack::isEmpty() {
39+
return _top <= -1;
40+
}
41+
42+
stack::stack() {
43+
_arr = (int *) malloc(M * sizeof(int));
44+
_top = -1;
45+
_capacity = M;
46+
}
47+
48+
stack::stack(int size) {
49+
_arr = (int *) malloc(size * sizeof(int));
50+
_top = -1;
51+
_capacity = size;
52+
}
53+
54+
stack::~stack() {
55+
if (_arr != nullptr) {
56+
free(_arr);
57+
_arr = nullptr;
58+
}
59+
}
60+
61+
inline
62+
void stack::push(int n) {
63+
if (isFull()) {
64+
// TODO: throw an exception.
65+
}
66+
_arr[++_top] = n;
67+
}
68+
69+
inline
70+
int stack::pop() {
71+
if (isEmpty()) {
72+
// TODO: throw an exception.
73+
}
74+
return _arr[_top--];
75+
}
76+
77+
inline
78+
int stack::top() {
79+
if (isEmpty()) {
80+
// TODO: throw an exception.
81+
}
82+
return _arr[_top];
83+
}
84+
85+
#endif // ifndef _STACK_HPP_

0 commit comments

Comments
 (0)