[Data Structure] Stack

Stack

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
#include <iostream>
using namespace std;
template <class T>
class Stack {
private:
T * data;
int size;
int head;
public:
Stack(int _s) : size(_s) {
if ((data = (T*)malloc(sizeof(T)*size)) == NULL) {
fprintf(stderr, "MALLOC ERROR\n");
}
head = 0;
}
Stack() {
size = 10;
if ((data = (T*)malloc(sizeof(T)*size)) == NULL) {
fprintf(stderr, "MALLOC ERROR\n");
}
head = 0;
}
void push(T d) {
if (head<size) { data[head++] = d; return; }
else {
size *= 2;
if ((data = (T*)realloc(data, sizeof(T)*size)) == NULL) {
fprintf(stderr, "REALLOC ERROR\n");
return;
}
data[head++] = d;
return;
}
}
void pop() { head--; }
T top() { return data[head - 1]; }
};
int main(int argc, char** argv) {
Stack<int> s;
for (int i = 0; i<13; i++)
s.push(i);
for (int i = 0; i<13; i++) {
cout << s.top() << endl;
s.pop();
}
return 0;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2020/07/21/DataStructure/stack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.