-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.h
136 lines (115 loc) · 2.25 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
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
/**~*~*
Stack template
*~**/
//
// Stack.h
//
// This is the header file for the Stack class.
//
// Minh An Cao
//
#ifndef DYNAMICSTACK_H
#define DYNAMICSTACK_H
#include <iostream>
using namespace std;
template <class T>
class Stack
{
private:
// Structure for the stach nodes
struct StackNode
{
T value; // Value in the node
StackNode *next; // Pointer to next node
};
StackNode *top; // Pointer to the stack top
int count;
public:
//Constructor
Stack(){top = NULL; count = 0;}
// Destructor
~Stack();
// Stack operations
bool push(T);
bool pop(T &);
bool isEmpty();
// getCount()
T getTop();
};
/**~*~*
Destructor
*~**/
template <class T>
Stack<T>::~Stack()
{
StackNode *currNode, *nextNode;
// Position nodePtr at the top of the stack.
currNode = top;
// Traverse the list deleting each node.
while (currNode) //while (currNode != NULL)
{
nextNode = currNode->next;
delete currNode;
currNode = nextNode;
}
}
/**~*~*
Member function push pushes the argument onto
the stack.
*~**/
template <class T>
bool Stack<T>::push(T item)
{
StackNode *newNode; // Pointer to a new node
// Allocate a new node and store num there.
newNode = new StackNode;
if (!newNode)
return false;
newNode->value = item;
// Update links and counter
newNode->next = top;
top = newNode;
count++;
return true;
}
/**~*~*
Member function pop pops the value at the top
of the stack off, and copies it into the variable
passed as an argument.
*~**/
template <class T>
bool Stack<T>::pop(T &item)
{
StackNode *temp; // Temporary pointer
// empty stack
if (count == 0)
return false;
// pop value off top of stack
item = top->value;
temp = top->next;
delete top;
top = temp;
count--;
return true;
}
/**~*~*
Member function isEmpty returns true if the stack
is empty, or false otherwise.
*~**/
template <class T>
bool Stack<T>::isEmpty()
{
return count == 0;
}
/**~*~*
Member function getTop assigns the parameter to the top item value and returns true, returns false otherwise
returns false otherwise
*~**/
template <class T>
T Stack<T>::getTop()
{
if (count == 0)
return NULL;
return top->value;
}
#endif