-
Notifications
You must be signed in to change notification settings - Fork 5
/
stack.h
63 lines (50 loc) · 1.16 KB
/
stack.h
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
//
// Created by codercat on 19-3-11.
//
#include <malloc.h>
#include <cstring>
#include <cassert>
#ifndef ALGORITHM_STACK_H
#define ALGORITHM_STACK_H
template<typename E>
class Stack {
private:
unsigned int capacity = 0;
unsigned int size = 0;
E *container;
public:
Stack(unsigned int capacity) {
assert(capacity > 0);
this->capacity = capacity;
this->container = new E[capacity];
memset(this->container, 0, capacity * sizeof(E));
}
void pop() {
assert(!this->isEmpty());
E top = this->container[this->getSize() - 1];
this->size--;
}
E top() {
assert(!this->isEmpty());
E top = this->container[this->getSize() - 1];
return top;
}
void push(E element) {
assert(!this->isFull());
this->container[this->getSize()] = element;
this->size++;
}
bool isEmpty() {
return this->getSize() == 0;
}
bool isFull() {
return this->getSize() == this->capacity;
}
unsigned int getSize() {
return this->size;
}
~Stack() {
free(this->container);
}
};
#endif //ALGORITHM_STACK_H