-
Notifications
You must be signed in to change notification settings - Fork 77
/
stack.cpp
91 lines (81 loc) · 1.79 KB
/
stack.cpp
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
#ifndef stack_H
#define stack_H
#include <bits/stdc++.h>
template <typename T>
class stack {
struct Node {
T data;
Node* next;
Node(T const& data, Node* next)
: data(data)
, next(next) {
}
Node(T&& data, Node* next)
: data(std::move(data))
, next(next) {
}
};
public:
~stack();
void push(T const& data);
void push(T&& data);
bool empty() const;
int size() const;
T top() const;
void pop();
void print(std::ostream& str = std::cout) const;
private:
Node* head = nullptr;
int elements = 0;
};
template<typename T>
stack<T>::~stack() {
Node* next;
for(Node* loop = head; loop != nullptr; loop = next) {
next = loop->next;
delete loop;
}
}
template<typename T>
void stack<T>::push(T const& data) {
head = new Node(data, head);
++elements;
}
template<typename T>
void stack<T>::push(T&& data) {
head = new Node(std::move(data), head);
++elements;
}
template<typename T>
bool stack<T>::empty() const {
return head == nullptr;
}
template<typename T>
int stack<T>::size() const {
return elements;
}
template<typename T>
T stack<T>::top() const {
if (head == nullptr) {
throw std::runtime_error("Invalid Action");
}
return head->data;
}
template<typename T>
void stack<T>::pop() {
if (head == nullptr) {
throw std::runtime_error("Invalid Action");
}
Node* tmp = head;
head = head->next;
--elements;
delete tmp;
}
template<typename T>
void stack<T>::print(std::ostream& str) const {
int id = 0;
for(Node* loop = head; loop != nullptr; loop = loop->next, ++id) {
str << "Element: " << id << " = " << loop->data << "\n";
}
}
#endif