-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.h
90 lines (82 loc) · 1.43 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
#pragma once
#include <exception>
#include <iostream>
using namespace std;
template <typename T>
class Stack
{
public:
Stack() : _top(nullptr), _size(0) {}
struct Node
{
Node(T el) : data(el), previous(nullptr) {}
Node(T el, Node* pr) : data(el), previous(pr) {}
Node* previous;
T data;
};
void push(const T);
void pop();
T& top();
T& prev();
int size();
private:
Node* _top;
int _size;
};
template <typename T>
void Stack<T>::push(const T el) {
try {
if (_top != nullptr) {
Node* temp = new Node(el, _top);
_top = temp;
}
else
{
_top = new Node(el);
}
_size++;
}
catch (bad_alloc) {
cerr << "Error: Bad_alloc\n";
}
}
template <typename T>
void Stack<T>::pop() {
try {
if (_top == nullptr)
throw out_of_range("Error: Out of range\n");
Node* temp = _top;
_top = _top->previous;
delete temp;
_size--;
}
catch (exception& e) {
cerr << e.what();
}
}
template <typename T>
T& Stack<T>::top() {
try {
if (_top == nullptr)
throw out_of_range("Erorr: Stack is empty\n");
return _top->data;
}
catch (exception& e) {
cerr << e.what();
}
}
template <typename T>
T& Stack<T>::prev() {
try {
if (_top == nullptr)
throw("Erorr: Stack is empty\n");
return _top->previous->data;
}
catch (exception& e) {
cerr << e.what();
}
}
template <typename T>
int Stack<T>::size() {
return _size;
}