-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStackLinked.h
More file actions
100 lines (86 loc) · 1.51 KB
/
StackLinked.h
File metadata and controls
100 lines (86 loc) · 1.51 KB
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
#if !defined (STACKLINKED_H)
#define STACKLINKED_H
#include "NextNode.h"
template < class T >
class StackLinked
{
private:
NextNode<T>* top;
int sze; // number of items in the stack
public:
StackLinked();
~StackLinked();
bool isEmpty();
int size();
void popAll();
T* pop();
void push(T* item);
T* peek();
};
template < class T >
StackLinked<T>::StackLinked()
{
top = NULL;
sze = 0;
}
template < class T >
StackLinked<T>::~StackLinked()
{
popAll();
}
template < class T >
bool StackLinked<T>::isEmpty()
{
return sze == 0;
}
template < class T >
int StackLinked<T>::size()
{
return sze;
}
template < class T >
void StackLinked<T>::popAll()
{
//loop over the stack, deleting the nodes
//the actual items are not deleted
if (sze == 0) return;
NextNode<T>* curr = top;
NextNode<T>* prev = NULL;
while (curr != NULL)
{
prev = curr;
curr = curr->getNext();
prev->setNext(NULL);
delete prev;
}
}
template < class T >
T* StackLinked<T>::peek()
{
T* item = NULL;
if (!isEmpty())
{
item = top->getItem();
}
return item;
}
template < class T >
void StackLinked<T>::push(T* item)
{
NextNode<T>* node = new NextNode<T>(item);
node->setNext(top);
top = node;
sze++;
}
template < class T >
T* StackLinked<T>::pop()
{
if (sze == 0) return NULL;
T* item = top->getItem();
NextNode<T>* temp = top->getNext();
delete top;
top = temp;
sze--;
return item;
}
#endif