-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.h
120 lines (96 loc) · 2.33 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
109
110
111
112
113
114
115
116
117
118
119
120
/*Function templates are special functions that can operate
with generic types. This allows us to create a function
template whose functionality can be adapted to more than
one type or class without repeating the entire code for each type.*/
/*To use this function template we use the following format for the function call:
function_name <type> (parameters);
*/
#ifndef STACK_H
#define STACK_H
#include "Output.h"
template <typename T>
class Stack {
public:
Stack();
~Stack();
bool isEmpty() const;
int size() const;
//Push: Place item on top of the stack
void push(const T& newItem);
//Top: Take a look at the topmost item without removing it
void getTop(T& stackTop) const;
//Pop: Remove item from the top of the stack
void pop();
void printWhole();
private:
struct ListNode {
T item;
ListNode* next;
};
ListNode* top;
ListNode* _last;
int _size;
};
template <typename T>
Stack<T>::~Stack(){}
template <typename T>
Stack<T>::Stack(){
this->_size = 0;
}
template <typename T>
int Stack<T>::size() const {
return this->_size;
}
template <typename T>
bool Stack<T>::isEmpty() const {
if(this->_size == 0)
return true;
return false;
}
template <typename T>
void Stack<T>::printWhole(){
for(ListNode* temp = top;temp!= NULL;temp=temp->next)
output<<temp->item->getName()<<endl;
}
template <typename T>
void Stack<T>::push(const T& newItem){
if(this->isEmpty()){
_last = new ListNode;
_last->next = NULL;
_last->item = newItem;
top = _last;
}
else{
ListNode* newNode = new ListNode;
newNode->item = newItem;
newNode->next = top;
top = newNode;
}
this->_size++;
}
template <typename T>
void Stack<T>::getTop(T& stackTop) const{
if(top==NULL){
cout<<"theres nothing to pop, stack is empty\n";
return;
}
stackTop = top->item;
}
template <typename T>
void Stack<T>::pop(){
if(top==NULL){
cout<<"theres nothing to pop, stack is empty\n";
return;
}
else if(top->next==NULL){
top=NULL;
_last = NULL;
}
else{
ListNode* tempNode = top->next;
delete top;
top = tempNode;
this->_size--;
}
}
#endif