-
Notifications
You must be signed in to change notification settings - Fork 363
/
stack.hpp
82 lines (71 loc) · 1.4 KB
/
stack.hpp
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
/*
Stack
-----
A data structure which has the Last In First Out (LIFO) property. Elements are added
and removed from the top (head). Only the top element can be accessed at any given time.
Hence, there is no random access. All member functions have O(1) time complexity.
*/
#ifndef STACK_HPP
#define STACK_HPP
#include "data_structure/linked_list/singly_linked_list.hpp"
template<class T>
class Stack {
private:
size_t size;
Node<T>* head;
public:
Stack();
void push(const T &item);
void pop();
T top();
size_t length();
bool isEmpty();
};
/*
Constructor
-----------
*/
template<class T>
Stack<T>::Stack() : size {0}, head {nullptr} {}
/*
Adds an item to the top of the stack
*/
template<class T>
void Stack<T>::push(const T &item) {
Node<T>* temp = new Node<T>(item, head);
head = temp;
++size;
}
/*
Removes an item from the top of the stack
*/
template<class T>
void Stack<T>::pop() {
Node<T>* temp = head;
head = temp->get_next();
temp->set_next(nullptr);
delete temp;
--size;
}
/*
Returns the top element of the stack
*/
template<class T>
T Stack<T>::top() {
return head->get_value();
}
/*
Returns the size of the stack
*/
template<class T>
size_t Stack<T>::length() {
return size;
}
/*
Returns true if stack is empty
*/
template<class T>
bool Stack<T>::isEmpty() {
return size == 0;
}
#endif /* STACK_HPP */