-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
stack.h
108 lines (91 loc) · 3.44 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
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
/***
* _ __ ___ _
* | |/ /___ ___ _ __ / __|__ _| |_ __
* | ' </ -_) -_) '_ \ | (__/ _` | | ' \
* |_|\_\___\___| .__/ \___\__,_|_|_|_|_|
* |_|
* _
* __ _ _ _ __| |
* / _` | ' \/ _` |
* \__,_|_||_\__,_|
*
* _ _ _ _ _ _
* | | ___ __ _ _ _ _ _ /_\ | |__ _ ___ _ _(_) |_| |_ _ __ ___
* | |__/ -_) _` | '_| ' \ / _ \| / _` / _ \ '_| | _| ' \| ' \(_-<
* |____\___\__,_|_| |_||_| /_/ \_\_\__, \___/_| |_|\__|_||_|_|_|_/__/
* |___/
* Yeah! Ravi let's do it!
*/
#ifndef STACK_H
#define STACK_H
#include <iostream>
#include <exception>
#include <cstdint>
namespace algo {
const uint32_t defaultCapacity = 500;
template <typename T = uintptr_t>
class Stack {
public:
Stack( uint32_t capacity = defaultCapacity )
: _capacity{ capacity }, _size{ 0 }, _elements{ new T[_capacity] }
{
}
Stack( const Stack & st )
: _capacity{ st.capacity }, _size{ st._size }, _elements{ new T[_capacity] }
{
for(uint32_t i = 0; i < _capacity; ++i) {
_elements[i] = st._elements[i];
}
}
bool empty()
{
return (_size == 0 );
}
void pop()
{
if (empty())
return;
_size--;
}
void push( const T & obj ) {
if ( _size == _capacity )
throw stack_out_of_bound_exception;
_elements[_size++] = obj;
}
const T & top()
{
if (empty())
throw stack_empty_exception;
return _elements[_size - 1];
}
uint32_t size()
{
return _size;
}
void print(std::ostream & out = std::cout)
{
for (int i = _size - 1; i >= 0; --i) {
out << _elements[i] << " ";
}
out << std::endl;
}
private:
uint32_t _capacity;
uint32_t _size;
T * _elements;
Stack & operator=(const Stack & st);
class StackEmptyException : public std::exception {
virtual const char * what() const throw()
{
return "Stack is empty";
}
} stack_empty_exception;
class StackOutofBoundException : public std::exception {
virtual const char * what() const throw()
{
return "Stack Index out of bound";
}
} stack_out_of_bound_exception ;
}; // end of class stack
} // end of namespace algo
#endif