-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstack.h
More file actions
44 lines (42 loc) · 838 Bytes
/
stack.h
File metadata and controls
44 lines (42 loc) · 838 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
#pragma once
#include <iostream>
#include <exception>
template <typename T> class Stack
{
template <typename T> class StackItem
{
public:
T value;
StackItem<T>* under;
StackItem(T value_, StackItem<T>* under_) : value(value_), under(under_) {};
~StackItem() { under = NULL; };
};
StackItem<T>* top;
bool isEmpty;
public:
Stack() : top(NULL), isEmpty(true) {};
~Stack()
{
while (!isEmpty)
Pop();
top = NULL;
}
void Push(T value_)
{
top = new StackItem<T>(value_, top);
isEmpty = false;
}
T Pop()
{
if (isEmpty)
throw std::out_of_range("Can't pop from an empty stack");
T toReturn = top->value;
StackItem<T>*tmp = top;
top = tmp->under;
delete tmp;
if (!top)
isEmpty = true;
return toReturn;
}
bool IsEmpty() const { return isEmpty; }
};